add_thing_notification.go 2.0 KB

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