update_thing_notification.go 2.3 KB

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