70 lines
1.7 KiB
Go
70 lines
1.7 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/iliadenisov/galaxy/internal/controller"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/iliadenisov/galaxy/internal/model/rest"
|
|
)
|
|
|
|
func CommandHandler(c *gin.Context, executor CommandExecutor) {
|
|
var cmd rest.Command
|
|
if errorResponded(c, c.ShouldBindJSON(&cmd)) {
|
|
return
|
|
}
|
|
|
|
commands := make([]Command, 0)
|
|
for i := range cmd.Commands {
|
|
command, err := parseCommand(cmd.Actor, cmd.Commands[i])
|
|
if errorResponded(c, err) {
|
|
return
|
|
}
|
|
commands = append(commands, command)
|
|
}
|
|
if len(commands) == 0 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "no commands given"})
|
|
return
|
|
}
|
|
|
|
if errorResponded(c, executor.Execute(commands...)) {
|
|
return
|
|
}
|
|
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
func parseCommand(actor string, c json.RawMessage) (Command, error) {
|
|
meta := new(rest.CommandMeta)
|
|
if err := json.Unmarshal(c, meta); err != nil {
|
|
return nil, err
|
|
}
|
|
switch t := meta.Type; t {
|
|
case rest.CommandTypeRaceVote:
|
|
return giveVotes(actor, c)
|
|
case rest.CommandTypeRaceRelation:
|
|
return updateRelation(actor, c)
|
|
default:
|
|
return nil, fmt.Errorf("unknown comman type: %s", t)
|
|
}
|
|
}
|
|
|
|
func giveVotes(actor string, c json.RawMessage) (Command, error) {
|
|
var v rest.CommandVote
|
|
if err := json.Unmarshal(c, &v); err != nil {
|
|
return nil, err
|
|
}
|
|
return func(c controller.Ctrl) error { return c.RaceVote(actor, v.Recipient) }, nil
|
|
}
|
|
|
|
func updateRelation(actor string, c json.RawMessage) (Command, error) {
|
|
var v rest.CommandUpdateRelation
|
|
if err := json.Unmarshal(c, &v); err != nil {
|
|
return nil, err
|
|
}
|
|
return func(c controller.Ctrl) error { return c.RaceRelation(actor, v.Opponent, v.Relation) }, nil
|
|
}
|