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