add_image.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. package image
  2. //go:generate mkdir -p mocks
  3. //go:generate rm -rf ./mocks/*_minimock.go
  4. //go:generate minimock -i TransactionManager,FileRepository,ThingImageRepository,PlaceImageRepository -o ./mocks/ -s "_minimock.go"
  5. import (
  6. "context"
  7. "mime/multipart"
  8. "path/filepath"
  9. "strconv"
  10. "time"
  11. "git.dmitriygnatenko.ru/dima/go-common/logger"
  12. "github.com/gofiber/fiber/v2"
  13. "git.dmitriygnatenko.ru/dima/homethings/internal/factory"
  14. "git.dmitriygnatenko.ru/dima/homethings/internal/helpers/random"
  15. "git.dmitriygnatenko.ru/dima/homethings/internal/mappers"
  16. "git.dmitriygnatenko.ru/dima/homethings/internal/models"
  17. )
  18. const fileDateLayout = "2006-01-02-15-04-05"
  19. type (
  20. TransactionManager interface {
  21. ReadCommitted(context.Context, func(ctx context.Context) error) error
  22. }
  23. FileRepository interface {
  24. Save(fctx *fiber.Ctx, header *multipart.FileHeader, path string) error
  25. Delete(path string) error
  26. }
  27. ThingImageRepository interface {
  28. Add(ctx context.Context, req models.AddThingImageRequest) error
  29. Get(ctx context.Context, id uint64) (*models.Image, error)
  30. GetByThingID(ctx context.Context, id uint64) ([]models.Image, error)
  31. GetByPlaceID(ctx context.Context, id uint64) ([]models.Image, error)
  32. Delete(ctx context.Context, id uint64) error
  33. }
  34. PlaceImageRepository interface {
  35. Add(ctx context.Context, req models.AddPlaceImageRequest) error
  36. Get(ctx context.Context, id uint64) (*models.Image, error)
  37. GetByPlaceID(ctx context.Context, id uint64) ([]models.Image, error)
  38. Delete(ctx context.Context, id uint64) error
  39. }
  40. )
  41. // @Router /api/v1/images [post]
  42. // @Param place_id formData int false "Place ID"
  43. // @Param thing_id formData int false "Thing ID"
  44. // @Param files formData []file true "Files"
  45. // @Success 200 {object} dto.EmptyResponse
  46. // @Failure 400 {object} dto.ErrorResponse
  47. // @Failure 500 {object} dto.ErrorResponse
  48. // @Summary Add images
  49. // @Tags Images
  50. // @security APIKey
  51. // @Accept mpfd
  52. // @Produce json
  53. func AddImageHandler(
  54. tm TransactionManager,
  55. fileRepository FileRepository,
  56. thingImageRepository ThingImageRepository,
  57. placeImageRepository PlaceImageRepository,
  58. ) fiber.Handler {
  59. return func(fctx *fiber.Ctx) error {
  60. var form *multipart.Form
  61. var placeID, thingID uint64
  62. var files []string
  63. var err error
  64. ctx := fctx.Context()
  65. if form, err = fctx.MultipartForm(); err != nil {
  66. logger.Info(ctx, err.Error())
  67. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  68. }
  69. if formPlace := form.Value["place_id"]; len(formPlace) > 0 {
  70. placeID, err = strconv.ParseUint(formPlace[0], 0, 64)
  71. if err != nil {
  72. logger.Info(ctx, err.Error())
  73. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  74. }
  75. }
  76. if formThing := form.Value["thing_id"]; len(formThing) > 0 {
  77. thingID, err = strconv.ParseUint(formThing[0], 0, 64)
  78. if err != nil {
  79. logger.Info(ctx, err.Error())
  80. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  81. }
  82. }
  83. date := time.Now().Format(fileDateLayout)
  84. for _, file := range form.File["files"] {
  85. filename := "/files/" + date + "_" + random.GenerateRandomString(10) + filepath.Ext(file.Filename)
  86. if err = fileRepository.Save(fctx, file, filename); err != nil {
  87. logger.Error(ctx, err.Error())
  88. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  89. }
  90. files = append(files, filename)
  91. }
  92. if (placeID == 0 && thingID == 0) || len(files) == 0 {
  93. return fiber.NewError(fiber.StatusBadRequest, "")
  94. }
  95. err = tm.ReadCommitted(ctx, func(ctx context.Context) error {
  96. if thingID > 0 {
  97. for _, file := range files {
  98. txErr := thingImageRepository.Add(ctx, mappers.ToAddThingImageRequest(thingID, file))
  99. if txErr != nil {
  100. return txErr
  101. }
  102. }
  103. } else {
  104. for _, file := range files {
  105. txErr := placeImageRepository.Add(ctx, mappers.ToAddPlaceImageRequest(placeID, file))
  106. if txErr != nil {
  107. return txErr
  108. }
  109. }
  110. }
  111. return nil
  112. })
  113. if err != nil {
  114. logger.Error(ctx, err.Error())
  115. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  116. }
  117. return fctx.JSON(factory.CreateEmptyResponse())
  118. }
  119. }