usermngmt/model/query.go

82 lines
1.6 KiB
Go
Raw Normal View History

2021-11-10 02:54:49 +00:00
package model
2021-11-09 04:48:24 +00:00
import (
"github.com/Selly-Modules/mongodb"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
2021-11-10 04:42:23 +00:00
// CommonQuery ...
2021-11-10 01:44:22 +00:00
type CommonQuery struct {
2021-11-09 04:48:24 +00:00
Page int64
Limit int64
Keyword string
RoleID string
Status string
2021-11-20 15:00:00 +00:00
Deleted string
2021-11-09 04:48:24 +00:00
Sort interface{}
2021-11-18 03:30:12 +00:00
Other map[string]interface{}
2021-11-09 04:48:24 +00:00
}
2021-11-20 15:00:00 +00:00
// AssignDeleted ...
func (q *CommonQuery) AssignDeleted(cond bson.M) {
if q.Deleted == "true" {
cond["deleted"] = true
}
if q.Deleted == "false" {
cond["deleted"] = false
}
}
2021-11-09 04:48:24 +00:00
// AssignKeyword ...
2021-11-10 01:44:22 +00:00
func (q *CommonQuery) AssignKeyword(cond bson.M) {
2021-11-09 04:48:24 +00:00
if q.Keyword != "" {
cond["searchString"] = mongodb.GenerateQuerySearchString(q.Keyword)
}
}
// AssignRoleID ...
2021-11-10 01:44:22 +00:00
func (q *CommonQuery) AssignRoleID(cond bson.M) {
2021-11-09 04:48:24 +00:00
if q.RoleID != "" {
if id, isValid := mongodb.NewIDFromString(q.RoleID); isValid {
cond["roleId"] = id
}
}
}
// AssignStatus ...
2021-11-10 01:44:22 +00:00
func (q *CommonQuery) AssignStatus(cond bson.M) {
2021-11-09 04:48:24 +00:00
if q.Status != "" {
cond["status"] = q.Status
}
}
// GetFindOptionsUsingPage ...
2021-11-10 01:44:22 +00:00
func (q *CommonQuery) GetFindOptionsUsingPage() *options.FindOptions {
2021-11-09 04:48:24 +00:00
opts := options.Find()
if q.Limit > 0 {
opts.SetLimit(q.Limit).SetSkip(q.Limit * q.Page)
}
if q.Sort != nil {
opts.SetSort(q.Sort)
}
return opts
}
// SetDefaultLimit ...
2021-11-10 01:44:22 +00:00
func (q *CommonQuery) SetDefaultLimit() {
2021-11-09 04:48:24 +00:00
if q.Limit <= 0 || q.Limit > 20 {
q.Limit = 20
}
}
2021-11-18 03:30:12 +00:00
// AssignOther ...
func (q *CommonQuery) AssignOther(cond bson.M) {
2021-12-07 07:28:52 +00:00
// Query fields in other object
2021-11-18 03:30:12 +00:00
if len(q.Other) > 0 {
for key, value := range q.Other {
cond["other."+key] = value
}
}
}