From 59d31f5e63acbc8805b8d59506ebca769a39c804 Mon Sep 17 00:00:00 2001 From: Hoang Date: Mon, 22 Nov 2021 16:02:55 +0700 Subject: [PATCH] add IsDeviceIDExistedMethod --- action_check_exists.go | 24 ++++++++++++++++++++++++ action_create.go | 2 +- db.go | 19 ------------------- 3 files changed, 25 insertions(+), 20 deletions(-) create mode 100644 action_check_exists.go 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() -}