add IsDeviceIDExistedMethod

This commit is contained in:
Hoang 2021-11-22 16:02:55 +07:00
parent b3a42ef4b2
commit 59d31f5e63
3 changed files with 25 additions and 20 deletions

24
action_check_exists.go Normal file
View File

@ -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()
}

View File

@ -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")
}

19
db.go
View File

@ -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()
}