usermngmt/db.go

103 lines
2.1 KiB
Go
Raw Permalink Normal View History

2021-11-08 08:34:20 +00:00
package usermngmt
import (
"context"
"fmt"
"github.com/Selly-Modules/logger"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
// getUserCollection ...
func (s Service) getUserCollection() *mongo.Collection {
2021-11-08 11:21:52 +00:00
return s.DB.Collection(fmt.Sprintf("%s-%s", s.TablePrefix, tableUser))
2021-11-08 08:34:20 +00:00
}
// getRoleCollection ...
func (s Service) getRoleCollection() *mongo.Collection {
2021-11-08 11:21:52 +00:00
return s.DB.Collection(fmt.Sprintf("%s-%s", s.TablePrefix, tableRole))
2021-11-08 08:34:20 +00:00
}
2021-11-08 10:04:01 +00:00
func (s Service) isPhoneNumberOrEmailExisted(ctx context.Context, phone, email string) bool {
2021-11-08 08:34:20 +00:00
var (
2021-11-08 10:04:01 +00:00
col = s.getUserCollection()
2021-11-08 08:34:20 +00:00
)
// Find
cond := bson.M{
"$or": []bson.M{
{
"phone": phone,
},
{
"email": email,
},
},
}
2021-11-08 10:04:01 +00:00
total, err := col.CountDocuments(ctx, cond)
if err != nil {
logger.Error("usermngmt - countUserByCondition", logger.LogData{
2021-11-08 08:34:20 +00:00
"condition": cond,
"err": err.Error(),
})
return true
}
2021-11-08 10:04:01 +00:00
return total != 0
2021-11-08 08:34:20 +00:00
}
2021-11-08 10:04:01 +00:00
func (s Service) isRoleIDExisted(ctx context.Context, roleID primitive.ObjectID) bool {
2021-11-08 08:34:20 +00:00
var (
2021-11-08 10:04:01 +00:00
col = s.getRoleCollection()
2021-11-08 08:34:20 +00:00
)
// Find
cond := bson.M{
"_id": roleID,
}
2021-11-08 10:04:01 +00:00
total, err := col.CountDocuments(ctx, cond)
if err != nil {
logger.Error("usermngmt - countRoleByCondition", logger.LogData{
2021-11-08 08:34:20 +00:00
"condition": cond,
"err": err.Error(),
})
return false
}
2021-11-08 10:04:01 +00:00
return total != 0
2021-11-08 08:34:20 +00:00
}
2021-11-08 11:21:52 +00:00
func (s Service) userCreate(ctx context.Context, doc User) error {
var (
col = s.getUserCollection()
)
_, err := col.InsertOne(ctx, doc)
if err != nil {
logger.Error("usermngmt - Create", logger.LogData{
"doc": doc,
"err": err.Error(),
})
return fmt.Errorf("error when create user: %s", err.Error())
}
return nil
}
2021-11-09 02:08:56 +00:00
func (s Service) userUpdateOneByCondition(ctx context.Context, cond interface{}, payload interface{}) error {
var (
col = s.getUserCollection()
)
_, err := col.UpdateOne(ctx, cond, payload)
if err != nil {
logger.Error("usermngmt - Update", logger.LogData{
"cond": cond,
"payload": payload,
"err": err.Error(),
})
return fmt.Errorf("error when update user: %s", err.Error())
}
return err
}