search_thing.go 1.2 KB

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