github.com/yusys-cloud/go-jsonstore-rest@v0.0.0-20230228115429-0a54aa4a27a6/rest/storage_search.go (about) 1 // Author: yangzq80@gmail.com 2 // Date: 2021-03-16 3 package rest 4 5 import ( 6 "encoding/json" 7 "github.com/thedevsaddam/gojsonq/v2" 8 "github.com/yusys-cloud/go-jsonstore-rest/model" 9 "strings" 10 ) 11 12 func (s *Storage) Search(search Search) *model.Response { 13 resp := model.NewResponse() 14 15 all := s.ReadAll(search.B, search.K).Data.Items 16 b, _ := json.Marshal(all) 17 18 jq := gojsonq.New().FromString(string(b)) 19 if search.Node != "" { 20 jq.From(search.Node) 21 } 22 if search.Value != "" && search.Key != "" { 23 //Multiple conditions dynamic search 24 if strings.Contains(search.Key, ",") { 25 ks := strings.Split(search.Key, ",") 26 vs := strings.Split(search.Value, ",") 27 for i := 0; i < len(ks); i++ { 28 if ks[i] != "" && vs[i] != "" { 29 if strings.Contains(vs[i], "|") { 30 jq.WhereIn(ks[i], strings.Split(vs[i], "|")) 31 } else { 32 if search.Relation == "like" { 33 jq.WhereContains(ks[i], vs[i]) 34 } else { 35 jq.WhereEqual(ks[i], vs[i]) 36 } 37 } 38 } 39 } 40 } else { 41 if strings.Contains(search.Value, "|") { 42 jq.WhereIn(search.Key, strings.Split(search.Value, "|")) 43 } else { 44 if search.Relation == "like" { 45 jq.WhereContains(search.Key, search.Value) 46 } else { 47 jq.WhereEqual(search.Key, search.Value) 48 } 49 } 50 } 51 } 52 53 if search.ShortBy != "" { 54 sts := strings.Split(search.ShortBy, ",") 55 jq.SortBy(sts[0], sts[1]) 56 } else { 57 jq.SortBy("k", "desc") 58 } 59 resp.Data.Total = len(jq.Get().([]interface{})) 60 // Offset and limit 61 if search.Page != 0 { 62 jq.Offset((search.Page - 1) * search.Size) 63 } 64 // limit 65 if search.Size != 0 { 66 jq.Limit(search.Size) 67 } 68 69 resp.Data.Items = jq.Get().([]interface{}) 70 71 return resp 72 } 73 74 func (s *Storage) SearchStruct(search Search, obj interface{}) *model.Response { 75 76 rs := s.Search(search) 77 78 for _, item := range rs.Data.Items.([]interface{}) { 79 in := item.(map[string]interface{})["v"].(map[string]interface{}) 80 jsonbody, _ := json.Marshal(in) 81 json.Unmarshal(jsonbody, &obj) 82 item.(map[string]interface{})["v"] = obj 83 } 84 85 return rs 86 }