From 0841789ac651071abc0dd3a38dd5884e9eeea0a0 Mon Sep 17 00:00:00 2001 From: totegamma Date: Mon, 26 Feb 2024 22:23:29 +0900 Subject: [PATCH] add getCharacterByID API --- cmd/api/main.go | 3 ++- x/character/handler.go | 24 +++++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/cmd/api/main.go b/cmd/api/main.go index f9c69a69..fc4e04bc 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -275,7 +275,8 @@ func main() { // character apiV1.PUT("/character", characterHandler.Put, auth.Restrict(auth.ISLOCAL)) - apiV1.GET("/characters", characterHandler.Get) + apiV1.GET("/character/:id", characterHandler.Get) + apiV1.GET("/characters", characterHandler.Query) apiV1.DELETE("/character/:id", characterHandler.Delete, auth.Restrict(auth.ISLOCAL)) // stream diff --git a/x/character/handler.go b/x/character/handler.go index ee44b5a7..0f925669 100644 --- a/x/character/handler.go +++ b/x/character/handler.go @@ -17,6 +17,7 @@ var tracer = otel.Tracer("character") // Handler is the interface for handling HTTP requests type Handler interface { Get(c echo.Context) error + Query(c echo.Context) error Put(c echo.Context) error Delete(c echo.Context) error } @@ -30,11 +31,32 @@ func NewHandler(service Service) Handler { return &handler{service: service} } -// Get returns a character by ID +// Get returns a character by id func (h handler) Get(c echo.Context) error { ctx, span := tracer.Start(c.Request().Context(), "HandlerGet") defer span.End() + id := c.Param("id") + if id == "" { + return c.JSON(http.StatusBadRequest, echo.Map{"error": "Invalid request", "message": "id is required"}) + } + + character, err := h.service.Get(ctx, id) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return c.JSON(http.StatusNotFound, echo.Map{"error": "Character not found"}) + } + return err + } + + return c.JSON(http.StatusOK, echo.Map{"status": "ok", "content": character}) +} + +// Query returns a character by author and schema +func (h handler) Query(c echo.Context) error { + ctx, span := tracer.Start(c.Request().Context(), "HandlerQuery") + defer span.End() + author := c.QueryParam("author") schema := c.QueryParam("schema")