nquest/pkg/controller/engine.go

80 lines
1.8 KiB
Go
Raw Normal View History

2023-11-01 23:21:12 +03:00
package controller
import (
"net/http"
"github.com/labstack/echo/v4"
2024-01-05 03:50:33 +03:00
"gitrepo.ru/neonxp/nquest/api"
2023-11-01 23:21:12 +03:00
"gitrepo.ru/neonxp/nquest/pkg/contextlib"
"gitrepo.ru/neonxp/nquest/pkg/models"
"gitrepo.ru/neonxp/nquest/pkg/service"
)
type Engine struct {
2024-01-05 03:50:33 +03:00
GameService *service.Game
EngineService *service.Engine
2023-11-01 23:21:12 +03:00
}
2024-01-05 03:50:33 +03:00
// (GET /engine/{uid})
func (ec *Engine) GameEngine(c echo.Context, uid int) error {
2023-11-01 23:21:12 +03:00
user := contextlib.GetUser(c)
2024-01-05 03:50:33 +03:00
game, err := ec.GameService.GetByID(c.Request().Context(), uint(uid))
2023-11-01 23:21:12 +03:00
if err != nil {
return err
}
2024-01-05 03:50:33 +03:00
cursor, err := ec.EngineService.GetState(c.Request().Context(), game, user)
2023-11-01 23:21:12 +03:00
if err != nil {
return err
}
2024-01-05 03:50:33 +03:00
return c.JSON(http.StatusOK, mapCursorToTask(cursor))
}
// (POST /engine/{uid}/code)
func (ec *Engine) EnterCode(c echo.Context, uid int) error {
user := contextlib.GetUser(c)
ctx := c.Request().Context()
game, err := ec.GameService.GetByID(ctx, uint(uid))
2023-11-01 23:21:12 +03:00
if err != nil {
return err
}
2024-01-05 03:50:33 +03:00
req := &api.EnterCodeJSONRequestBody{}
if err := c.Bind(req); err != nil {
return err
}
cursor, err := ec.EngineService.EnterCode(ctx, game, user, req.Code)
2023-11-01 23:21:12 +03:00
if err != nil {
return err
}
2024-01-05 03:50:33 +03:00
return c.JSON(http.StatusOK, mapCursorToTask(cursor))
2023-11-01 23:21:12 +03:00
}
2024-01-05 03:50:33 +03:00
func mapCursorToTask(cursor *models.GameCursor) *api.TaskView {
resp := &api.TaskResponse{
Codes: make([]api.CodeView, 0, len(cursor.Task.Codes)),
Entered: make([]api.CodeView, 0, len(cursor.Codes)),
Solutions: []api.SolutionView{},
Text: cursor.Task.Text,
Title: cursor.Task.Title,
}
for _, code := range cursor.Task.Codes {
resp.Codes = append(resp.Codes, api.CodeView{
Description: code.Description,
})
}
for _, code := range cursor.Codes {
resp.Entered = append(resp.Entered, api.CodeView{
Code: &code.Code,
Description: code.Description,
})
}
return resp
2023-11-01 23:21:12 +03:00
}