Skip to content

Commit

Permalink
[prices] added whole word search
Browse files Browse the repository at this point in the history
  • Loading branch information
DictumMortuum committed Nov 21, 2023
1 parent 8e2271b commit a9c1445
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
2 changes: 1 addition & 1 deletion cmd/servus-prices/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

func Version(c *gin.Context) {
rs := map[string]any{
"version": "v0.0.8",
"version": "v0.0.9",
}
c.AbortWithStatusJSON(200, rs)
}
Expand Down
25 changes: 20 additions & 5 deletions pkg/middleware/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ func Paginate(c *gin.Context) {
}
}

func argToGorm(db *gorm.DB, key string, val any) *gorm.DB {
func argToGorm(db *gorm.DB, key string, val any, whole bool) *gorm.DB {
if key == "whole" {
return db
}

if strings.Contains(key, "@not") {
key = strings.Split(key, "@")[0]
return db.Not(key, val)
Expand All @@ -54,11 +58,15 @@ func argToGorm(db *gorm.DB, key string, val any) *gorm.DB {
return db.Where(key+" >= ?", val)
} else if strings.Contains(key, "@autolike") {
key = strings.Split(key, "@")[0]
terms := strings.Split(sanitize.AlphaNumeric(val.(string), true), " ")
temp := strings.TrimSpace(sanitize.AlphaNumeric(val.(string), true))
terms := strings.Split(temp, " ")

for _, term := range terms {
term = "%" + term + "%"
db = db.Where(key+" COLLATE utf8mb4_unicode_ci LIKE ?", term)
if whole {
db = db.Where(key + " COLLATE utf8mb4_unicode_ci REGEXP '[[:<:]]" + term + "[[:>:]]'")
} else {
db = db.Where(key+" COLLATE utf8mb4_unicode_ci LIKE ?", "%"+term+"%")
}
}

return db
Expand Down Expand Up @@ -87,12 +95,19 @@ func filter(c *gin.Context) func(db *gorm.DB) *gorm.DB {
if err != nil {
return db
} else {
whole := false
if val, ok := payload["whole"]; ok {
if val.(float64) == 1 {
whole = true
}
}

for key, val := range payload {
switch val.(type) {
case map[string]any:
continue
default:
db = argToGorm(db, key, val)
db = argToGorm(db, key, val, whole)
}
}

Expand Down

0 comments on commit a9c1445

Please sign in to comment.