search_thing.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package thing
  2. import (
  3. "net/url"
  4. "regexp"
  5. "strings"
  6. "git.dmitriygnatenko.ru/dima/go-common/logger"
  7. "github.com/gofiber/fiber/v2"
  8. "git.dmitriygnatenko.ru/dima/homethings/internal/helpers/location"
  9. "git.dmitriygnatenko.ru/dima/homethings/internal/mappers"
  10. )
  11. // @Router /api/v1/things/search/{search} [get]
  12. // @Param search path string true "Search string"
  13. // @Success 200 {object} dto.ThingResponse
  14. // @Failure 400 {object} dto.ErrorResponse
  15. // @Failure 500 {object} dto.ErrorResponse
  16. // @Summary Search things
  17. // @Tags Things
  18. // @security APIKey
  19. // @Accept json
  20. // @Produce json
  21. func SearchThingHandler(thingRepository ThingRepository) fiber.Handler {
  22. return func(fctx *fiber.Ctx) error {
  23. ctx := fctx.Context()
  24. search, _ := url.QueryUnescape(fctx.Params("search", ""))
  25. if match, _ := regexp.MatchString("^[A-Za-zА-Яа-я0-9 ]+$", search); !match {
  26. return fiber.NewError(fiber.StatusBadRequest, "")
  27. }
  28. search = strings.TrimSpace(search)
  29. if len([]rune(search)) < 3 {
  30. return fiber.NewError(fiber.StatusBadRequest, "")
  31. }
  32. res, err := thingRepository.Search(ctx, search)
  33. if err != nil {
  34. logger.Error(ctx, err.Error())
  35. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  36. }
  37. res = location.ApplyLocation(fctx, res)
  38. return fctx.JSON(mappers.ToThingsResponse(res))
  39. }
  40. }