Files
galaxy-game/internal/router/handler/command.go
T
2026-02-08 20:47:46 +02:00

48 lines
1.3 KiB
Go

package handler
import (
"errors"
"net/http"
"github.com/iliadenisov/galaxy/internal/controller"
"github.com/iliadenisov/galaxy/internal/game"
"github.com/gin-gonic/gin"
"github.com/iliadenisov/galaxy/internal/model/rest"
)
type CommandExecutor func(controller.Configurer, rest.Command) error
var (
ErrCommandNotProcessed = errors.New("command was not processed by executor")
)
func CommandHandler(c *gin.Context, configurer controller.Configurer, executor CommandExecutor) {
var cmd rest.Command
if err := c.ShouldBindJSON(&cmd); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err := executor(configurer, cmd)
switch {
case err == nil:
c.Status(http.StatusOK)
case errors.Is(err, ErrCommandNotProcessed):
c.Status(http.StatusInternalServerError) // TODO: add error text?
default:
// TODO: separate invalid input and game state errors
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
func ExecuteCommand(config controller.Configurer, cmd rest.Command) error {
switch {
case cmd.DeclareWar != nil:
return game.DeclareWar(config, cmd.Race, cmd.DeclareWar.Opponent)
case cmd.DeclarePeace != nil:
return game.DeclarePeace(config, cmd.Race, cmd.DeclareWar.Opponent)
default:
return ErrCommandNotProcessed
}
}