2022-08-16 16:35:45 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2022-08-17 15:32:42 +02:00
|
|
|
"fmt"
|
2022-08-16 16:35:45 +02:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/lyx0/nourybot/internal/data"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (app *application) showCommandHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
name, err := app.readCommandNameParam(r)
|
|
|
|
if err != nil {
|
2022-08-16 18:05:55 +02:00
|
|
|
app.logError(r, err)
|
2022-08-16 16:35:45 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the data for a specific movie from our helper method,
|
|
|
|
// then check if an error was returned, and which.
|
|
|
|
command, err := app.Models.Commands.Get(name)
|
|
|
|
if err != nil {
|
|
|
|
switch {
|
|
|
|
case errors.Is(err, data.ErrRecordNotFound):
|
2022-08-16 18:05:55 +02:00
|
|
|
app.logError(r, err)
|
2022-08-16 16:35:45 +02:00
|
|
|
return
|
|
|
|
default:
|
|
|
|
app.serverErrorResponse(w, r, err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2022-08-16 18:05:55 +02:00
|
|
|
app.Logger.Infow("GET Command",
|
|
|
|
"Command", command,
|
|
|
|
)
|
|
|
|
err = app.writeJSON(w, http.StatusOK, envelope{"command": command}, nil)
|
|
|
|
if err != nil {
|
|
|
|
app.serverErrorResponse(w, r, err)
|
|
|
|
}
|
2022-08-16 16:35:45 +02:00
|
|
|
}
|
|
|
|
|
2022-08-17 15:32:42 +02:00
|
|
|
func (app *application) createCommandHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var input struct {
|
|
|
|
Name string `json:"name"`
|
|
|
|
Text string `json:"text"`
|
|
|
|
Category string `json:"category"`
|
|
|
|
Level int `json:"level"`
|
|
|
|
}
|
2022-08-16 16:35:45 +02:00
|
|
|
|
2022-08-17 15:32:42 +02:00
|
|
|
err := app.readJSON(w, r, &input)
|
2022-08-16 16:35:45 +02:00
|
|
|
if err != nil {
|
2022-08-17 15:32:42 +02:00
|
|
|
app.badRequestResponse(w, r, err)
|
|
|
|
return
|
2022-08-16 16:35:45 +02:00
|
|
|
}
|
|
|
|
|
2022-08-17 15:32:42 +02:00
|
|
|
command := &data.Command{
|
|
|
|
Name: input.Name,
|
|
|
|
Text: input.Text,
|
|
|
|
Category: input.Category,
|
|
|
|
Level: input.Level,
|
|
|
|
}
|
2022-08-16 16:35:45 +02:00
|
|
|
|
2022-08-17 15:32:42 +02:00
|
|
|
err = app.Models.Commands.Insert(command)
|
|
|
|
if err != nil {
|
|
|
|
app.serverErrorResponse(w, r, err)
|
|
|
|
return
|
2022-08-16 16:35:45 +02:00
|
|
|
}
|
|
|
|
|
2022-08-17 15:32:42 +02:00
|
|
|
headers := make(http.Header)
|
|
|
|
headers.Set("Location", fmt.Sprintf("/v1/commands/%s", command.Name))
|
2022-08-16 16:35:45 +02:00
|
|
|
|
2022-08-17 15:32:42 +02:00
|
|
|
err = app.writeJSON(w, http.StatusCreated, envelope{"command": command}, headers)
|
|
|
|
if err != nil {
|
|
|
|
app.serverErrorResponse(w, r, err)
|
|
|
|
}
|
2022-08-16 16:35:45 +02:00
|
|
|
}
|
2022-08-17 15:32:42 +02:00
|
|
|
|
|
|
|
type envelope map[string]interface{}
|