/
search_mgm.go
259 lines (241 loc) · 5.96 KB
/
search_mgm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
* @Author: lwnmengjing
* @Date: 2023/1/25 17:14:19
* @Last Modified by: lwnmengjing
* @Last Modified time: 2023/1/25 17:14:19
*/
package actions
import (
"fmt"
"net/http"
"reflect"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/kamva/mgm/v3"
"github.com/kamva/mgm/v3/builder"
"github.com/kamva/mgm/v3/field"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/mss-boot-io/mss-boot/pkg"
"github.com/mss-boot-io/mss-boot/pkg/response"
"github.com/mss-boot-io/mss-boot/pkg/search/mgos"
)
// Pagination pagination params
type Pagination struct {
Page int64 `form:"page" query:"page"`
PageSize int64 `form:"pageSize" query:"pageSize"`
}
func (e *Pagination) GetPage() int64 {
if e.Page <= 0 {
return 1
}
return e.Page
}
func (e *Pagination) GetPageSize() int64 {
if e.PageSize <= 0 {
return 10
}
return e.PageSize
}
// Search action
type Search struct {
Base
Search response.Searcher
}
// NewSearchMgm new search action
func NewSearchMgm(m mgm.Model, search response.Searcher) *Search {
return &Search{
Base: Base{ModelMgm: m},
Search: search,
}
}
// String action name
func (*Search) String() string {
return "search"
}
// Handler action handler
func (e *Search) Handler() gin.HandlerFunc {
return func(c *gin.Context) {
if e.ModelMgm != nil {
e.searchMgm(c)
return
}
if e.ModelGorm != nil {
e.searchGorm(c)
return
}
response.Error(c,
http.StatusNotImplemented,
fmt.Errorf("not implemented"))
}
}
func (e *Search) searchMgm(c *gin.Context) {
req := pkg.DeepCopy(e.Search).(response.Searcher)
api := response.Make(c).Bind(req)
if api.Error != nil {
api.Err(http.StatusUnprocessableEntity)
return
}
filter, sort := mgos.MakeCondition(req)
count, err := mgm.Coll(e.ModelMgm).CountDocuments(c, filter)
if err != nil {
api.Log.Errorf("count items error, %s", err.Error())
api.AddError(err)
api.Err(http.StatusInternalServerError)
return
}
linkConfigs := getLinkTag(e.ModelMgm)
if len(linkConfigs) == 0 {
ops := options.Find()
ops.SetLimit(req.GetPageSize())
if len(sort) > 0 {
ops.SetSort(sort)
}
ops.SetSkip(req.GetPageSize() * (req.GetPage() - 1))
result, err := mgm.Coll(e.ModelMgm).Find(c, filter, ops)
if err != nil {
api.Log.Errorf("find items error, %s", err.Error())
api.AddError(err)
api.Err(http.StatusInternalServerError)
return
}
defer result.Close(c)
items := make([]any, 0, req.GetPageSize())
for result.Next(c) {
m := pkg.ModelDeepCopy(e.ModelMgm)
err = result.Decode(m)
if err != nil {
api.AddError(err)
api.Err(http.StatusInternalServerError)
return
}
items = append(items, m)
}
api.PageOK(items, count, req.GetPage(), req.GetPageSize())
}
//use Aggregate
//https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
pipeline := bson.A{
//builder.S(builder.Lookup(authorColl.Name(), "author_id", field.ID, "author")),
}
for i := range linkConfigs {
pipeline = append(pipeline,
builder.S(
builder.Lookup(
linkConfigs[i].CollectionName,
linkConfigs[i].LocalField,
field.ID, linkConfigs[i].ForeignField)))
}
//limit skip sort
pipeline = append(pipeline, bson.D{
{"$limit", req.GetPageSize()},
}, bson.D{
{"$skip", req.GetPageSize() * (req.GetPage() - 1)},
}, bson.D{
{"$sort", sort},
})
result, err := mgm.Coll(e.ModelMgm).Aggregate(c, pipeline)
if err != nil {
api.Log.Errorf("find items error, %s", err.Error())
api.AddError(err)
api.Err(http.StatusInternalServerError)
return
}
defer result.Close(c)
items := make([]any, 0, req.GetPageSize())
for result.Next(c) {
m := pkg.ModelDeepCopy(e.ModelMgm)
var bm bson.M
err = result.Decode(bm)
if err != nil {
api.AddError(err)
api.Err(http.StatusInternalServerError)
return
}
//todo bson.M to model
BsonMTransferModel(bm, m)
items = append(items, m)
}
api.PageOK(items, count, req.GetPage(), req.GetPageSize())
}
type LinkConfig struct {
FieldName string
CollectionName string
LocalField string
ForeignField string
}
func BsonMTransferModel(bm bson.M, model any) (err error) {
typeOf := reflect.TypeOf(model).Elem()
valueOf := reflect.ValueOf(model).Elem()
for i := 0; i < typeOf.NumField(); i++ {
f := typeOf.Field(i)
tagBson := f.Tag.Get("bson")
if tagBson == "-" {
continue
}
if tagBson == "" {
tagBson = f.Name
}
if f.Type.Kind() == reflect.Struct {
if f.Type.Name() == "mgm.DefaultModel" {
dm := valueOf.Field(i).Interface().(mgm.DefaultModel)
dm.SetID(bm["_id"].(primitive.ObjectID))
dm.UpdatedAt = bm["updated_at"].(time.Time)
dm.CreatedAt = bm["created_at"].(time.Time)
continue
}
if strings.Contains(tagBson, "inline") {
err = BsonMTransferModel(bm, valueOf.Field(i).Interface())
if err != nil {
return
}
continue
}
continue
}
if f.Type.Kind() == reflect.Array {
// transfer bson.M to array model
switch ms := bm[tagBson].(type) {
case []bson.M:
bsonBytes, _ := bson.Marshal(ms)
err = bson.Unmarshal(bsonBytes, valueOf.Field(i).Interface())
if err != nil {
return
}
default:
return fmt.Errorf("type %s not is array", reflect.TypeOf(ms).String())
}
continue
}
valueOf.Field(i).Set(reflect.ValueOf(bm[tagBson]))
}
return
}
// getLinkTag get link tag from object
func getLinkTag(model any) []LinkConfig {
configs := make([]LinkConfig, 0)
typeOf := reflect.TypeOf(model).Elem()
valueOf := reflect.ValueOf(model).Elem()
for i := 0; i < typeOf.NumField(); i++ {
f := typeOf.Field(i)
if f.Type.Kind() == reflect.Struct {
if f.Type.String() == "mgm.DefaultModel" {
continue
}
vm, ok := valueOf.Field(i).Interface().(mgm.Model)
if !ok {
continue
}
m := pkg.ModelDeepCopy(vm)
configs = append(configs, LinkConfig{
FieldName: f.Tag.Get("bson"),
CollectionName: mgm.Coll(m).Name(),
LocalField: f.Name + field.ID,
ForeignField: field.ID,
})
}
}
return configs
}