100 lines
2.6 KiB
Go
100 lines
2.6 KiB
Go
package dao
|
|
|
|
import (
|
|
"context"
|
|
|
|
"cid/model/entity"
|
|
"gitee.com/red-future---jilin-g/common/mongo"
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
|
)
|
|
|
|
var Strategy = &strategyDao{
|
|
NoCache: true,
|
|
}
|
|
|
|
type strategyDao struct {
|
|
NoCache bool
|
|
}
|
|
|
|
func (d *strategyDao) SetNoCache() {
|
|
Strategy.NoCache = true
|
|
}
|
|
|
|
// GetByName 根据名称获取策略
|
|
func (d *strategyDao) GetByName(ctx context.Context, name string) (strategy *entity.Strategy, err error) {
|
|
err = mongo.FindOne(ctx, d.NoCache, bson.M{"name": name}, &strategy, "strategies")
|
|
return
|
|
}
|
|
|
|
// GetByID 根据ID获取策略
|
|
func (d *strategyDao) GetByID(ctx context.Context, id string) (strategy *entity.Strategy, err error) {
|
|
err = mongo.FindOne(ctx, d.NoCache, bson.M{"_id": id}, &strategy, "strategies")
|
|
return
|
|
}
|
|
|
|
// GetByTenantLevel 根据租户级别获取策略
|
|
func (d *strategyDao) GetByTenantLevel(ctx context.Context, tenantLevel string) (strategy *entity.Strategy, err error) {
|
|
err = mongo.FindOne(ctx, d.NoCache, bson.M{"tenantLevel": tenantLevel, "status": "active"}, &strategy, "strategies",
|
|
options.FindOne().SetSort(bson.M{"priority": -1, "createdAt": 1}))
|
|
return
|
|
}
|
|
|
|
// Create 创建策略
|
|
func (d *strategyDao) Create(ctx context.Context, strategy *entity.Strategy) (id string, err error) {
|
|
ids, err := mongo.Insert(ctx, []interface{}{strategy}, "strategies")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(ids) > 0 {
|
|
id = ids[0].(string)
|
|
}
|
|
return
|
|
}
|
|
|
|
// Update 更新策略
|
|
func (d *strategyDao) Update(ctx context.Context, strategy *entity.Strategy) (affected int64, err error) {
|
|
result, err := mongo.Update(ctx, bson.M{"_id": strategy.Id}, bson.M{"$set": strategy}, "strategies")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.ModifiedCount, nil
|
|
}
|
|
|
|
// Delete 删除策略
|
|
func (d *strategyDao) Delete(ctx context.Context, id string) (affected int64, err error) {
|
|
count, err := mongo.Delete(ctx, bson.M{"_id": id}, "strategies")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
// GetList 获取策略列表
|
|
func (d *strategyDao) GetList(ctx context.Context, page, size int, tenantLevel, status string) (list []*entity.Strategy, total int64, err error) {
|
|
filter := bson.M{}
|
|
|
|
// 筛选条件
|
|
if tenantLevel != "" {
|
|
filter["tenantLevel"] = tenantLevel
|
|
}
|
|
if status != "" {
|
|
filter["status"] = status
|
|
}
|
|
|
|
// 获取总数
|
|
total, err = mongo.Count(ctx, d.NoCache, filter, "strategies")
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
// 分页查询
|
|
offset := (page - 1) * size
|
|
err = mongo.Find(ctx, d.NoCache, filter, &list, "strategies",
|
|
options.Find().SetSort(bson.M{"priority": -1, "createdAt": -1}).
|
|
SetSkip(int64(offset)).
|
|
SetLimit(int64(size)))
|
|
|
|
return
|
|
}
|