usermngmt/model/query.go

106 lines
2.0 KiB
Go
Raw Permalink 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"
2021-12-24 02:38:49 +00:00
"go.mongodb.org/mongo-driver/bson/primitive"
2021-11-09 04:48:24 +00:00
"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{}
2022-03-25 07:16:52 +00:00
RoleIDs []primitive.ObjectID
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
}
}
}
2022-03-25 07:16:52 +00:00
// AssignRoleIDs ...
func (q *CommonQuery) AssignRoleIDs(cond bson.M) {
if len(q.RoleIDs) == 1 {
cond["roleId"] = q.RoleIDs[0]
} else if len(q.RoleIDs) > 1 {
cond["roleId"] = bson.M{
"$in": q.RoleIDs,
}
}
}
2021-11-09 04:48:24 +00:00
// 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 {
2021-12-24 02:38:49 +00:00
switch v := value.(type) {
case []primitive.ObjectID:
cond["other."+key] = bson.M{
"$in": v,
}
case []string:
cond["other."+key] = bson.M{
"$in": v,
}
default:
cond["other."+key] = value
}
2021-11-18 03:30:12 +00:00
}
}
}