search_thing.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package thing
  2. import (
  3. "net/url"
  4. "regexp"
  5. "strings"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/helpers"
  7. "git.dmitriygnatenko.ru/dima/homethings/internal/interfaces"
  8. "git.dmitriygnatenko.ru/dima/homethings/internal/mappers"
  9. "github.com/gofiber/fiber/v2"
  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(sp interfaces.ServiceProvider) 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 := sp.GetThingRepository().Search(ctx, search)
  33. if err != nil {
  34. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  35. }
  36. res = helpers.ApplyLocation(fctx, res)
  37. return fctx.JSON(mappers.ConvertToThingsResponseDTO(res))
  38. }
  39. }