delete_thing_image.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package image
  2. import (
  3. "database/sql"
  4. "errors"
  5. "github.com/gofiber/fiber/v2"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/factory"
  7. )
  8. // @Router /api/v1/images/thing/{imageId} [delete]
  9. // @Param imageId path int true "Image ID"
  10. // @Success 200 {object} dto.EmptyResponse
  11. // @Failure 400 {object} dto.ErrorResponse
  12. // @Failure 500 {object} dto.ErrorResponse
  13. // @Summary Delete image
  14. // @Tags Images
  15. // @security APIKey
  16. // @Accept json
  17. // @Produce json
  18. func DeleteThingImageHandler(
  19. fileRepository FileRepository,
  20. thingImageRepository ThingImageRepository,
  21. ) fiber.Handler {
  22. return func(fctx *fiber.Ctx) error {
  23. ctx := fctx.Context()
  24. id, err := fctx.ParamsInt("imageId")
  25. if err != nil {
  26. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  27. }
  28. image, err := thingImageRepository.Get(ctx, id)
  29. if err != nil {
  30. if errors.Is(err, sql.ErrNoRows) {
  31. return fiber.NewError(fiber.StatusBadRequest, "")
  32. }
  33. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  34. }
  35. if err = thingImageRepository.Delete(ctx, id, nil); err != nil {
  36. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  37. }
  38. if err = fileRepository.Delete(image.Image); err != nil {
  39. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  40. }
  41. return fctx.JSON(factory.CreateEmptyResponse())
  42. }
  43. }