Add filtration for GET /catalog EP.

Filtration enables where passing in template like this isFilter=1&<property_code>=<value1>,<value2>
features/feature-catalog-redis
Ernest Litvinenko 2024-03-18 05:58:15 +03:00
parent 54856057c2
commit 32efec31e2
2 changed files with 40 additions and 2 deletions

View File

@ -12,8 +12,11 @@ func (h *handlers) GetCatalogItems(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10")) limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
offset := (page - 1) * limit offset := (page - 1) * limit
if c.DefaultQuery("isFilter", "0") == "0" {
c.JSON(200, services.GetCatalogItems(limit, offset)) c.JSON(200, services.GetCatalogItems(limit, offset))
return
}
c.JSON(200, services.FilterCatalogItems(c.Request.URL.Query()))
} }
func (h *handlers) GetCatalogItem(c *gin.Context) { func (h *handlers) GetCatalogItem(c *gin.Context) {

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"relynolli-server/internal" "relynolli-server/internal"
"relynolli-server/models" "relynolli-server/models"
"strings"
) )
func retrieveItems(stmt string, structure interface{}) { func retrieveItems(stmt string, structure interface{}) {
@ -55,3 +56,37 @@ func GetCatalogItemById(id int) (models.CatalogStructWeb, error) {
} }
return retrieveCatalogItems(stmt)[0], nil return retrieveCatalogItems(stmt)[0], nil
} }
func FilterCatalogItems(filters map[string][]string) []models.CatalogStructWeb {
// Generate stmt
propertiesSubStmt := "properties->>'$.%s' = '%s'"
stmt := "select * from api_catalog where %s"
sample := "(%s)"
filterList := [][]string{}
for key, filter := range filters {
if key == "isFilter" {
continue
}
subFilterArr := []string{}
values := strings.Split(filter[0], ",")
for _, val := range values {
subFilterArr = append(subFilterArr, fmt.Sprintf(propertiesSubStmt, key, val))
}
filterList = append(filterList, subFilterArr)
}
samples := []string{}
for _, arr := range filterList {
samples = append(samples, fmt.Sprintf(sample, strings.Join(arr, " or ")))
}
stmt = fmt.Sprintf(stmt, strings.Join(samples, " and "))
println(stmt)
return retrieveCatalogItems(stmt)
}