fix(controller): db device operations consistency
This commit is contained in:
parent
921a869ca1
commit
f4a8f42dbe
|
|
@ -3,6 +3,7 @@ package db
|
|||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
|
|
@ -16,6 +17,7 @@ type Database struct {
|
|||
devices *mongo.Collection
|
||||
users *mongo.Collection
|
||||
ctx context.Context
|
||||
m *sync.Mutex
|
||||
}
|
||||
|
||||
func NewDatabase(ctx context.Context, mongoUri string) Database {
|
||||
|
|
@ -43,6 +45,8 @@ func NewDatabase(ctx context.Context, mongoUri string) Database {
|
|||
db.devices = devices
|
||||
db.users = users
|
||||
db.ctx = ctx
|
||||
db.m = &sync.Mutex{}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,6 +43,9 @@ func (d *Database) CreateDevice(device Device) error {
|
|||
var result bson.M
|
||||
var deviceExistent Device
|
||||
|
||||
d.m.Lock()
|
||||
defer d.m.Unlock()
|
||||
|
||||
/* ------------------ Do not overwrite status of other mtp ------------------ */
|
||||
err := d.devices.FindOne(d.ctx, bson.D{{"sn", device.SN}}, nil).Decode(&deviceExistent)
|
||||
if err == nil {
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ import (
|
|||
func (d *Database) UpdateStatus(sn string, status Status, mtp MTP) error {
|
||||
var result Device
|
||||
|
||||
d.m.Lock()
|
||||
defer d.m.Unlock()
|
||||
err := d.devices.FindOne(d.ctx, bson.D{{"sn", sn}}, nil).Decode(&result)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user