update_thing_notification.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package notification
  2. import (
  3. "database/sql"
  4. "github.com/go-playground/validator/v10"
  5. "github.com/gofiber/fiber/v2"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/dto"
  7. "git.dmitriygnatenko.ru/dima/homethings/internal/factory"
  8. "git.dmitriygnatenko.ru/dima/homethings/internal/helpers"
  9. "git.dmitriygnatenko.ru/dima/homethings/internal/mappers"
  10. )
  11. // @Router /api/v1/things/notifications/{thingId} [put]
  12. // @Param thingId path int true "Thing ID"
  13. // @Param data body dto.UpdateThingNotificationRequest true "Request body"
  14. // @Success 200 {object} dto.ThingNotificationResponse
  15. // @Failure 400 {object} dto.ErrorResponse
  16. // @Failure 500 {object} dto.ErrorResponse
  17. // @Summary Update thing notification
  18. // @Tags Notifications
  19. // @security APIKey
  20. // @Accept json
  21. // @Produce json
  22. func UpdateThingNotificationHandler(
  23. thingNotificationRepository ThingNotificationRepository,
  24. ) fiber.Handler {
  25. return func(fctx *fiber.Ctx) error {
  26. ctx := fctx.Context()
  27. id, err := fctx.ParamsInt("thingId")
  28. if err != nil {
  29. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  30. }
  31. req := dto.UpdateThingNotificationRequest{}
  32. if err = fctx.BodyParser(&req); err != nil {
  33. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  34. }
  35. var validate = validator.New()
  36. if err = validate.Struct(req); err != nil {
  37. return fctx.Status(fiber.StatusBadRequest).JSON(factory.CreateValidateErrorResponse(err))
  38. }
  39. _, err = thingNotificationRepository.Get(ctx, id)
  40. if err != nil {
  41. if err == sql.ErrNoRows {
  42. return fiber.NewError(fiber.StatusBadRequest, "")
  43. }
  44. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  45. }
  46. dbReq, err := mappers.ToUpdateThingNotificationRequest(id, req)
  47. if err != nil {
  48. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  49. }
  50. if err = thingNotificationRepository.Update(ctx, *dbReq, nil); err != nil {
  51. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  52. }
  53. res, err := thingNotificationRepository.Get(ctx, id)
  54. if err != nil {
  55. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  56. }
  57. res = helpers.ApplyLocation(fctx, res)
  58. return fctx.JSON(mappers.ToThingNotificationResponse(*res))
  59. }
  60. }