diff --git a/action_check_exists.go b/action_check_exists.go new file mode 100644 index 0000000..14ae682 --- /dev/null +++ b/action_check_exists.go @@ -0,0 +1,24 @@ +package devicemngmt + +import ( + "context" + + "github.com/Selly-Modules/logger" + "go.mongodb.org/mongo-driver/bson" +) + +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("devicemngmt - findByDeviceID", logger.LogData{ + "deviceId": deviceID, + "err": err.Error(), + }) + return true + } + return !device.ID.IsZero() +} diff --git a/action_create.go b/action_create.go index 8f53290..79a9663 100644 --- a/action_create.go +++ b/action_create.go @@ -40,7 +40,7 @@ func (s Service) Create(payload CreateOptions) error { deviceData := payload.newDevice() // Find deviceID existed or not - if s.isDeviceIDExisted(ctx, deviceData.DeviceID) { + if s.IsDeviceIDExisted(ctx, deviceData.DeviceID) { return errors.New("this device is already existed") } diff --git a/db.go b/db.go index 5aae623..865ecb1 100644 --- a/db.go +++ b/db.go @@ -1,11 +1,8 @@ package devicemngmt import ( - "context" "fmt" - "github.com/Selly-Modules/logger" - "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) @@ -16,19 +13,3 @@ func (s Service) getDeviceCollection() *mongo.Collection { } return s.DB.Collection(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("devicemngmt - findByDeviceID", logger.LogData{ - "deviceId": deviceID, - "err": err.Error(), - }) - return true - } - return !device.ID.IsZero() -}