add updateMethod #2

Merged
lqhoang99 merged 1 commits from feature/UpdateMethod into master 2021-11-09 02:29:15 +00:00
3 changed files with 125 additions and 0 deletions
Showing only changes of commit a4ae19667f - Show all commits

57
action_update.go Normal file
View File

@ -0,0 +1,57 @@
package usermngmt
import (
"context"
"github.com/Selly-Modules/mongodb"
"go.mongodb.org/mongo-driver/bson"
)
// UpdateOptions ...
type UpdateOptions struct {
Name string
Phone string
Email string
RoleID string
Other string
}
// UpdateByUserID ...
func (s Service) UpdateByUserID(userID string, payload UpdateOptions) error {
var (
ctx = context.Background()
)
// Validate payload
err := payload.validate(ctx)
if err != nil {
return err
}
// Setup condition
id, _ := mongodb.NewIDFromString(userID)
cond := bson.M{
"_id": id,
}
// Setup update data
roleID, _ := mongodb.NewIDFromString(payload.RoleID)
updateData := bson.M{
"$set": bson.M{
"name": payload.Name,
"phone": payload.Phone,
"email": payload.Email,
"roleId": roleID,
"other": payload.Other,
"updatedAt": now(),
},
}
// Update
err = s.userUpdateOneByCondition(ctx, cond, updateData)
if err != nil {
return err
}
return nil
}

18
db.go
View File

@ -83,3 +83,21 @@ func (s Service) userCreate(ctx context.Context, doc User) error {
return nil return nil
} }
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
}

View File

@ -73,3 +73,53 @@ func (co CreateOptions) validate(ctx context.Context) error {
return nil return nil
} }
func (co UpdateOptions) validate(ctx context.Context) error {
// Name
if co.Name == "" {
logger.Error("usermngmt - Update: no name data", logger.LogData{
"payload": co,
})
return errors.New("no name data")
}
// Phone
if co.Phone == "" {
logger.Error("usermngmt - Update: no phone data", logger.LogData{
"payload": co,
})
return errors.New("no phone data")
}
// Email
if co.Email == "" {
logger.Error("usermngmt - Update: no email data", logger.LogData{
"payload": co,
})
return errors.New("no email data")
}
// RoleID
if co.RoleID == "" {
logger.Error("usermngmt - Update: no roleID data", logger.LogData{
"payload": co,
})
return errors.New("no role id data")
}
// Find roleID exists or not
roleID, isValid := mongodb.NewIDFromString(co.RoleID)
if !isValid {
return errors.New("invalid role id data")
}
if !s.isRoleIDExisted(ctx, roleID) {
return errors.New("role id does not exist")
}
// Find phone number,email exists or not
if s.isPhoneNumberOrEmailExisted(ctx, co.Phone, co.Email) {
return errors.New("phone number or email already existed")
}
return nil
}