mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-26 11:24:54 +00:00
change set to transaction
This commit is contained in:
@ -10,7 +10,13 @@ import { GetDeviceDetailsFunctionsStatusInterface } from 'src/device/interfaces/
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { firebaseDataBase } from '../../firebase.config';
|
||||
import { Database, DataSnapshot, get, ref, set } from 'firebase/database';
|
||||
import {
|
||||
Database,
|
||||
DataSnapshot,
|
||||
get,
|
||||
ref,
|
||||
runTransaction,
|
||||
} from 'firebase/database';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
@Injectable()
|
||||
export class DeviceStatusFirebaseService {
|
||||
@ -154,8 +160,12 @@ export class DeviceStatusFirebaseService {
|
||||
this.firebaseDb,
|
||||
`device-status/${addDeviceStatusDto.deviceUuid}`,
|
||||
);
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
const existingData = snapshot.val() || {};
|
||||
|
||||
// Use a transaction to handle concurrent updates
|
||||
await runTransaction(dataRef, (existingData) => {
|
||||
if (!existingData) {
|
||||
existingData = {};
|
||||
}
|
||||
|
||||
// Assign default values if fields are not present
|
||||
if (!existingData.deviceTuyaUuid) {
|
||||
@ -187,6 +197,11 @@ export class DeviceStatusFirebaseService {
|
||||
code,
|
||||
value,
|
||||
}));
|
||||
|
||||
return existingData;
|
||||
});
|
||||
|
||||
// Save logs to your repository
|
||||
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
||||
return this.deviceStatusLogRepository.create({
|
||||
deviceId: addDeviceStatusDto.deviceUuid,
|
||||
@ -200,10 +215,9 @@ export class DeviceStatusFirebaseService {
|
||||
});
|
||||
});
|
||||
await this.deviceStatusLogRepository.save(newLogs);
|
||||
// Save the updated data to Firebase
|
||||
await set(dataRef, existingData);
|
||||
|
||||
// Return the updated data
|
||||
return existingData;
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
return snapshot.val();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user