fix(controller): db device operations consistency

This commit is contained in:
leandrofars 2024-02-19 22:07:54 -03:00
parent 921a869ca1
commit f4a8f42dbe
3 changed files with 9 additions and 0 deletions

View File

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

View File

@ -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 {

View File

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