build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
index 91a2d426e0a0c6b62bb3887317c211e3b7090ab5..fb7062674bb2ea14787a2d5eb0ff6646bab75d11 100644 (file)
@@ -2,11 +2,8 @@
 
 import fs from 'node:fs';
 
-import lockfile from 'proper-lockfile';
-
 import { FileType, type Statistics } from '../../types';
-import { FileUtils } from '../../utils/FileUtils';
-import { Utils } from '../../utils/Utils';
+import { AsyncLock, AsyncLockType, Constants, FileUtils, Utils } from '../../utils';
 import { Storage } from '../internal';
 
 export class JsonFileStorage extends Storage {
@@ -19,38 +16,35 @@ export class JsonFileStorage extends Storage {
 
   public storePerformanceStatistics(performanceStatistics: Statistics): void {
     this.checkPerformanceRecordsFile();
-    lockfile
-      .lock(this.dbName, { stale: 5000, retries: 3 })
-      .then(async (release) => {
-        try {
-          const fileData = fs.readFileSync(this.dbName, 'utf8');
-          const performanceRecords: Statistics[] = fileData
-            ? (JSON.parse(fileData) as Statistics[])
-            : [];
-          performanceRecords.push(performanceStatistics);
-          fs.writeFileSync(
-            this.dbName,
-            Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
-            'utf8'
-          );
-        } catch (error) {
-          FileUtils.handleFileException(
-            this.dbName,
-            FileType.PerformanceRecords,
-            error as NodeJS.ErrnoException,
-            this.logPrefix
-          );
-        }
-        await release();
+    AsyncLock.acquire(AsyncLockType.performance)
+      .then(() => {
+        const fileData = fs.readFileSync(this.dbName, 'utf8');
+        const performanceRecords: Statistics[] = fileData
+          ? (JSON.parse(fileData) as Statistics[])
+          : [];
+        performanceRecords.push(performanceStatistics);
+        fs.writeFileSync(
+          this.dbName,
+          Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
+          'utf8'
+        );
+      })
+      .catch((error) => {
+        FileUtils.handleFileException(
+          this.dbName,
+          FileType.PerformanceRecords,
+          error as NodeJS.ErrnoException,
+          this.logPrefix
+        );
       })
-      .catch(() => {
-        /* This is intentional */
+      .finally(() => {
+        AsyncLock.release(AsyncLockType.performance).catch(Constants.EMPTY_FUNCTION);
       });
   }
 
   public open(): void {
     try {
-      if (this?.fd === undefined || this?.fd === null) {
+      if (Utils.isNullOrUndefined(this?.fd)) {
         this.fd = fs.openSync(this.dbName, 'a+');
       }
     } catch (error) {