diff --git a/action_create.go b/action_create.go index 2781186..36413d8 100644 --- a/action_create.go +++ b/action_create.go @@ -7,7 +7,6 @@ import ( "github.com/Selly-Modules/logger" "github.com/Selly-Modules/mongodb" - "go.mongodb.org/mongo-driver/bson" ) // CreateOptions ... @@ -41,15 +40,8 @@ func (s Service) Create(payload CreateOptions) error { return err } - // Find device id existed or not - device := Device{} - if err = col.FindOne(ctx, bson.M{"deviceID": deviceData.DeviceID}).Decode(&device); err != nil { - logger.Error("devicemngt - findByDeviceID", logger.LogData{ - "deviceID": deviceData.DeviceID, - "err": err.Error(), - }) - } - if !device.ID.IsZero() { + // Find deviceID existed or not + if s.isDeviceIDExisted(ctx, deviceData.DeviceID) { return errors.New("this device is already existed") } diff --git a/helper.go b/helper.go index 3c1d026..3441415 100644 --- a/helper.go +++ b/helper.go @@ -1,9 +1,12 @@ package devicemngmt import ( + "context" "fmt" + "github.com/Selly-Modules/logger" ua "github.com/mssola/user_agent" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) @@ -12,6 +15,25 @@ func (s Service) getDeviceCollection() *mongo.Collection { return s.DB.Collection(fmt.Sprintf("%s-%s", s.TablePrefix, tableDevice)) } +func (s Service) isDeviceIDExisted(ctx context.Context, deviceID string) bool { + var ( + col = s.getDeviceCollection() + device = Device{} + ) + + if err := col.FindOne(ctx, bson.M{"deviceID": deviceID}).Decode(&device); err != nil { + logger.Error("devicemngt - findByDeviceID", logger.LogData{ + "deviceID": deviceID, + "err": err.Error(), + }) + } + if !device.ID.IsZero() { + return true + } + + return false +} + func getOSName(userAgent string) string { uaData := ua.New(userAgent) return uaData.OSInfo().Name diff --git a/model.go b/model.go index 22a2796..33dce53 100644 --- a/model.go +++ b/model.go @@ -9,7 +9,7 @@ import ( // Device ... type Device struct { ID primitive.ObjectID `bson:"_id" json:"_id"` - DeviceID string `bson:"deviceID" json:"deviceID"` // unique + DeviceID string `bson:"deviceID" json:"deviceId"` // unique IP string `bson:"ip" json:"ip"` OSName string `bson:"osName" json:"osName"` OSVersion string `bson:"osVersion" json:"osVersion"` @@ -17,7 +17,7 @@ type Device struct { Language string `bson:"language" json:"language"` // vi, en IsMobile bool `bson:"isMobile" json:"isMobile"` LastActivityAt time.Time `bson:"lastActivityAt" json:"lastActivityAt"` - UserID primitive.ObjectID `bson:"userID" json:"userID"` + UserID primitive.ObjectID `bson:"userID" json:"userId"` AuthToken string `bson:"authToken" json:"authToken"` FCMToken string `bson:"fcmToken" json:"fcmToken"` CreatedAt time.Time `bson:"createdAt" json:"createdAt"`