usermngmt/action_create.go

70 lines
1.4 KiB
Go
Raw Normal View History

2021-11-08 04:53:03 +00:00
package usermngmt
import (
"context"
"fmt"
"github.com/Selly-Modules/logger"
"github.com/Selly-Modules/mongodb"
2021-11-08 08:34:20 +00:00
"go.mongodb.org/mongo-driver/bson/primitive"
2021-11-08 04:53:03 +00:00
)
// CreateOptions ...
type CreateOptions struct {
2021-11-08 10:04:01 +00:00
Name string
Phone string
Email string
Password string
Status string
RoleID primitive.ObjectID
Other string
2021-11-08 04:53:03 +00:00
}
// Create ...
func (s Service) Create(payload CreateOptions) error {
var (
col = s.getUserCollection()
ctx = context.Background()
)
// Validate payload
2021-11-08 10:04:01 +00:00
err := payload.validate(ctx)
2021-11-08 04:53:03 +00:00
if err != nil {
return err
}
// New user data from payload
userData, err := payload.newUser()
if err != nil {
return err
}
// Create device
_, err = col.InsertOne(ctx, userData)
if err != nil {
2021-11-08 10:04:01 +00:00
logger.Error("usermngmt - Create", logger.LogData{
2021-11-08 04:53:03 +00:00
"doc": userData,
"err": err.Error(),
})
return fmt.Errorf("error when create user: %s", err.Error())
}
return nil
}
func (payload CreateOptions) newUser() (result User, err error) {
timeNow := now()
return User{
2021-11-08 08:34:20 +00:00
ID: mongodb.NewObjectID(),
Name: payload.Name,
Phone: payload.Phone,
Email: payload.Email,
2021-11-08 10:04:01 +00:00
HashedPassword: hashPassword(payload.Password),
2021-11-08 08:34:20 +00:00
Status: payload.Status,
RoleID: payload.RoleID,
Other: payload.Other,
CreatedAt: timeNow,
UpdatedAt: timeNow,
2021-11-08 04:53:03 +00:00
}, nil
}