get_thing.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package thing
  2. import (
  3. "database/sql"
  4. "errors"
  5. "github.com/gofiber/fiber/v2"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/helpers"
  7. "git.dmitriygnatenko.ru/dima/homethings/internal/mappers"
  8. )
  9. // @Router /api/v1/things/{thingId} [get]
  10. // @Param thingId path int true "Thing ID"
  11. // @Success 200 {object} dto.ThingResponse
  12. // @Failure 404 {object} dto.EmptyResponse
  13. // @Failure 400 {object} dto.ErrorResponse
  14. // @Failure 500 {object} dto.ErrorResponse
  15. // @Summary Get one thing
  16. // @Tags Things
  17. // @security APIKey
  18. // @Accept json
  19. // @Produce json
  20. func GetThingHandler(thingRepository ThingRepository) fiber.Handler {
  21. return func(fctx *fiber.Ctx) error {
  22. ctx := fctx.Context()
  23. id, err := fctx.ParamsInt("thingId")
  24. if err != nil {
  25. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  26. }
  27. res, err := thingRepository.Get(ctx, id)
  28. if err != nil {
  29. if errors.Is(err, sql.ErrNoRows) {
  30. return fiber.NewError(fiber.StatusNotFound, "")
  31. }
  32. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  33. }
  34. res = helpers.ApplyLocation(fctx, res)
  35. return fctx.JSON(mappers.ToThingResponse(*res))
  36. }
  37. }