usermngmt/role/db.go

93 lines
1.9 KiB
Go
Raw Normal View History

2021-11-10 01:44:22 +00:00
package role
import (
"context"
2021-11-10 07:50:43 +00:00
"fmt"
2023-04-05 10:54:05 +00:00
"log"
2021-11-10 01:44:22 +00:00
2021-11-16 04:11:04 +00:00
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
2021-11-10 07:50:43 +00:00
"go.mongodb.org/mongo-driver/mongo/options"
2023-04-05 10:54:05 +00:00
"git.selly.red/Selly-Modules/usermngmt/database"
"git.selly.red/Selly-Modules/usermngmt/model"
2021-11-10 01:44:22 +00:00
)
2021-11-10 07:50:43 +00:00
func create(ctx context.Context, doc model.DBRole) error {
var (
col = database.GetRoleCol()
)
_, err := col.InsertOne(ctx, doc)
if err != nil {
return fmt.Errorf("error when create role: %s", err.Error())
}
return nil
}
func updateOneByCondition(ctx context.Context, cond interface{}, payload interface{}) error {
var (
col = database.GetRoleCol()
)
_, err := col.UpdateOne(ctx, cond, payload)
if err != nil {
return fmt.Errorf("error when update role: %s", err.Error())
}
return err
}
func findByCondition(ctx context.Context, cond interface{}, opts ...*options.FindOptions) (docs []model.DBRole) {
var (
col = database.GetRoleCol()
)
docs = make([]model.DBRole, 0)
cursor, err := col.Find(ctx, cond, opts...)
if err != nil {
2023-04-05 10:54:05 +00:00
log.Printf("usermngmt.findByCondition - Role - Find cond: %v, opts: %v\n", cond, opts)
2021-11-10 07:50:43 +00:00
return
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &docs); err != nil {
return
}
return
}
// countByCondition ...
func countByCondition(ctx context.Context, cond interface{}) int64 {
var (
col = database.GetRoleCol()
)
total, err := col.CountDocuments(ctx, cond)
if err != nil {
2023-04-05 10:54:05 +00:00
log.Println("usermngmt.countByCondition - Role: ", err)
2021-11-10 07:50:43 +00:00
}
return total
}
2021-11-16 04:11:04 +00:00
func isRoleIDExisted(ctx context.Context, roleID primitive.ObjectID) bool {
var (
col = database.GetRoleCol()
)
// Find
cond := bson.M{
"_id": roleID,
}
total, err := col.CountDocuments(ctx, cond)
if err != nil {
return false
}
return total != 0
2021-11-19 06:50:24 +00:00
}
func findByID(ctx context.Context, id primitive.ObjectID) (model.DBRole, error) {
var (
doc model.DBRole
col = database.GetRoleCol()
)
err := col.FindOne(ctx, bson.M{"_id": id}).Decode(&doc)
return doc, err
}