zdravko/internal/handlers/api.go

73 lines
1.7 KiB
Go
Raw Normal View History

package handlers
import (
"context"
2024-02-27 11:04:05 +00:00
"database/sql"
2024-02-23 11:18:02 +00:00
"errors"
"net/http"
2024-02-27 11:04:05 +00:00
"code.tjo.space/mentos1386/zdravko/database/models"
"code.tjo.space/mentos1386/zdravko/internal/services"
"code.tjo.space/mentos1386/zdravko/pkg/api"
"github.com/labstack/echo/v4"
)
type ApiV1WorkersConnectGETResponse struct {
Endpoint string `json:"endpoint"`
Group string `json:"group"`
}
func (h *BaseHandler) ApiV1WorkersConnectGET(c echo.Context) error {
2024-02-23 11:18:02 +00:00
ctx := context.Background()
cc := c.(AuthenticatedContext)
2024-02-27 11:04:05 +00:00
workerGroup, err := services.GetWorkerGroup(ctx, h.db, cc.Principal.Worker.Group)
2024-02-23 11:18:02 +00:00
if err != nil {
2024-02-27 11:04:05 +00:00
if errors.Is(err, sql.ErrNoRows) {
2024-02-23 11:18:02 +00:00
return echo.NewHTTPError(http.StatusUnauthorized, "Token invalid")
}
return err
}
response := ApiV1WorkersConnectGETResponse{
Endpoint: h.config.Temporal.ServerHost,
2024-02-29 22:42:56 +00:00
Group: workerGroup.Id,
}
return c.JSON(http.StatusOK, response)
}
// TODO: Can we instead get this from the Workflow outcome?
//
// To somehow listen for the outcomes and then store them automatically.
func (h *BaseHandler) ApiV1MonitorsHistoryPOST(c echo.Context) error {
ctx := context.Background()
2024-02-29 22:42:56 +00:00
id := c.Param("id")
var body api.ApiV1MonitorsHistoryPOSTBody
2024-02-23 14:16:51 +00:00
err := (&echo.DefaultBinder{}).BindBody(c, &body)
if err != nil {
return err
}
2024-02-29 22:42:56 +00:00
_, err = services.GetMonitor(ctx, h.db, id)
if err != nil {
2024-02-27 11:04:05 +00:00
if err == sql.ErrNoRows {
return echo.NewHTTPError(http.StatusNotFound, "Monitor not found")
}
return err
}
2024-02-27 11:04:05 +00:00
err = services.AddHistoryForMonitor(ctx, h.db, &models.MonitorHistory{
2024-02-29 22:42:56 +00:00
MonitorId: id,
WorkerGroupId: body.WorkerGroupId,
Status: body.Status,
Note: body.Note,
2024-02-27 11:04:05 +00:00
})
if err != nil {
return err
}
return c.JSON(http.StatusCreated, map[string]string{"status": "ok"})
}