nquest/pkg/controller/admin.go

99 lines
2.2 KiB
Go
Raw Normal View History

2023-11-19 22:54:54 +03:00
package controller
import (
"net/http"
2024-01-20 21:37:49 +03:00
"time"
2023-11-19 22:54:54 +03:00
"github.com/google/uuid"
2023-11-19 22:54:54 +03:00
"github.com/labstack/echo/v4"
"gitrepo.ru/neonxp/nquest/api"
"gitrepo.ru/neonxp/nquest/pkg/contextlib"
2024-01-05 03:50:33 +03:00
"gitrepo.ru/neonxp/nquest/pkg/models"
2023-11-19 22:54:54 +03:00
"gitrepo.ru/neonxp/nquest/pkg/service"
)
type Admin struct {
GameService *service.Game
}
2024-01-05 03:50:33 +03:00
// (POST /admin/games)
func (a *Admin) CreateGame(ctx echo.Context) error {
2023-11-19 22:54:54 +03:00
user := contextlib.GetUser(ctx)
2024-01-05 03:50:33 +03:00
req := &api.GameEditRequest{}
if err := ctx.Bind(req); err != nil {
return err
}
game := a.mapCreateGameRequest(req, user)
var err error
game, err = a.GameService.CreateGame(ctx.Request().Context(), game)
2023-11-19 22:54:54 +03:00
if err != nil {
return err
}
2024-01-05 03:50:33 +03:00
return ctx.JSON(http.StatusCreated, api.GameResponse{
2024-01-20 21:37:49 +03:00
Authors: make([]api.UserView, 0, len(game.Authors)),
CreatedAt: game.CreatedAt.Format(time.RFC3339),
Description: game.Description,
Icon: game.IconID,
Id: game.ID,
2024-01-20 21:37:49 +03:00
Points: game.Points,
TaskCount: len(game.Tasks),
2024-01-05 03:50:33 +03:00
Title: game.Title,
2024-01-20 21:37:49 +03:00
Type: api.MapGameTypeReverse(game.Type),
2024-01-05 03:50:33 +03:00
})
}
func (*Admin) mapCreateGameRequest(req *api.GameEditRequest, user *models.User) *models.Game {
game := &models.Game{
Model: models.Model{
ID: uuid.New(),
},
2024-01-05 03:50:33 +03:00
Visible: false,
Title: req.Title,
Description: req.Description,
Authors: []*models.User{
user,
},
Type: api.MapGameType(req.Type),
Tasks: make([]*models.Task, 0, len(req.Tasks)),
Points: req.Points,
2024-01-20 21:37:49 +03:00
IconID: req.Icon,
2024-01-05 03:50:33 +03:00
}
for order, te := range req.Tasks {
2024-01-05 03:50:33 +03:00
task := &models.Task{
Model: models.Model{
ID: uuid.New(),
},
2024-01-05 03:50:33 +03:00
Title: te.Title,
Text: te.Text,
MaxTime: 0,
Solutions: make([]*models.Solution, 0, len(te.Solutions)),
Codes: make([]*models.Code, 0, len(te.Codes)),
TaskOrder: uint(order),
2024-01-05 03:50:33 +03:00
}
for _, s := range te.Solutions {
task.Solutions = append(task.Solutions, &models.Solution{
Model: models.Model{
ID: uuid.New(),
},
2024-01-05 03:50:33 +03:00
After: s.After,
Text: s.Text,
})
}
for _, ce := range te.Codes {
task.Codes = append(task.Codes, &models.Code{
Model: models.Model{
ID: uuid.New(),
},
2024-01-05 03:50:33 +03:00
Code: ce.Code,
Description: ce.Description,
})
}
game.Tasks = append(game.Tasks, task)
2023-11-19 22:54:54 +03:00
}
2024-01-05 03:50:33 +03:00
return game
2023-11-19 22:54:54 +03:00
}