devicemngmt/action_create.go

95 lines
2.0 KiB
Go
Raw Normal View History

2021-11-05 07:21:57 +00:00
package devicemngmt
import (
"context"
"errors"
2021-11-05 08:40:07 +00:00
"fmt"
2021-11-05 07:21:57 +00:00
"github.com/Selly-Modules/logger"
"github.com/Selly-Modules/mongodb"
)
2021-11-05 08:40:07 +00:00
// CreateOptions ...
type CreateOptions struct {
2021-11-05 09:57:33 +00:00
DeviceID string
UserID string
UserAgent string
AppVersion string
IP string
FCMToken string
AuthToken string
Language string
Model string
Manufacturer string
2021-12-10 04:46:25 +00:00
OsName string
OsVersion string
IsMobile bool
2021-11-05 07:21:57 +00:00
}
// Create ...
2021-11-05 08:40:07 +00:00
func (s Service) Create(payload CreateOptions) error {
2021-11-05 07:21:57 +00:00
var (
col = s.getDeviceCollection()
ctx = context.Background()
)
2021-11-05 08:40:07 +00:00
// Validate payload
err := payload.validate()
if err != nil {
return err
}
2021-11-05 07:21:57 +00:00
// New device data from payload
2021-11-08 02:46:17 +00:00
deviceData := payload.newDevice()
2021-11-05 07:21:57 +00:00
2021-11-05 09:10:12 +00:00
// Find deviceID existed or not
2021-11-22 09:05:28 +00:00
if s.IsDeviceIDExisted(deviceData.DeviceID) {
2021-11-05 08:40:07 +00:00
return errors.New("this device is already existed")
2021-11-05 07:21:57 +00:00
}
// Create device
_, err = col.InsertOne(ctx, deviceData)
if err != nil {
2021-11-10 10:08:39 +00:00
logger.Error("devicemngmt - Create ", logger.LogData{
2022-10-05 10:23:29 +00:00
Source: "devicemngmt.Create",
Message: err.Error(),
Data: deviceData,
2021-11-05 07:21:57 +00:00
})
2021-11-05 08:40:07 +00:00
return fmt.Errorf("error when create device: %s", err.Error())
2021-11-05 07:21:57 +00:00
}
return nil
}
2021-11-08 02:46:17 +00:00
func (payload CreateOptions) newDevice() Device {
2021-11-05 07:21:57 +00:00
timeNow := now()
2021-11-08 02:46:17 +00:00
// Get userAgent data
osName, osVersion, isMobile := getUserAgentData(payload.UserAgent)
2021-12-10 04:46:25 +00:00
if osName == "" || osVersion == "" {
osName = payload.OsName
osVersion = payload.OsVersion
isMobile = payload.IsMobile
}
2021-11-22 08:14:36 +00:00
userID, _ := mongodb.NewIDFromString(payload.UserID)
2021-11-08 02:46:17 +00:00
return Device{
2021-11-05 09:24:53 +00:00
ID: mongodb.NewObjectID(),
DeviceID: payload.DeviceID,
2021-11-08 02:46:17 +00:00
OSName: osName,
OSVersion: osVersion,
2021-11-05 09:24:53 +00:00
IP: payload.IP,
Language: getLanguage(payload.Language),
AuthToken: payload.AuthToken,
LastActivatedAt: timeNow,
CreatedAt: timeNow,
FCMToken: payload.FCMToken,
2021-11-05 09:57:33 +00:00
Model: payload.Model,
Manufacturer: payload.Manufacturer,
2021-11-22 08:14:36 +00:00
UserID: userID,
2021-11-08 02:46:17 +00:00
IsMobile: isMobile,
AppVersion: payload.AppVersion,
2021-11-05 07:21:57 +00:00
}
}