// Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
-import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs';
+import { closeSync, existsSync, mkdirSync, openSync, writeSync } from 'node:fs';
import { dirname } from 'node:path';
import { Storage } from './Storage';
} from '../../utils';
export class JsonFileStorage extends Storage {
- private fd: number | null = null;
+ private static readonly performanceRecords: Map<string, Statistics> = new Map<
+ string,
+ Statistics
+ >();
+
+ private fd?: number;
constructor(storageUri: string, logPrefix: string) {
super(storageUri, logPrefix);
this.checkPerformanceRecordsFile();
AsyncLock.acquire(AsyncLockType.performance)
.then(() => {
- const fileData = readFileSync(this.dbName, 'utf8');
- const performanceRecords: Statistics[] = fileData
- ? (JSON.parse(fileData) as Statistics[])
- : [];
- performanceRecords.push(performanceStatistics);
- writeFileSync(this.dbName, JSONStringifyWithMapSupport(performanceRecords, 2), 'utf8');
+ JsonFileStorage.performanceRecords.set(performanceStatistics.id, performanceStatistics);
+ writeSync(
+ this.fd!,
+ JSONStringifyWithMapSupport([...JsonFileStorage.performanceRecords.values()], 2),
+ 0,
+ 'utf8',
+ );
})
.catch((error) => {
handleFileException(
if (!existsSync(dirname(this.dbName))) {
mkdirSync(dirname(this.dbName), { recursive: true });
}
- this.fd = openSync(this.dbName, 'a+');
+ this.fd = openSync(this.dbName, 'w+');
}
} catch (error) {
handleFileException(
try {
if (this?.fd) {
closeSync(this.fd);
- this.fd = null;
+ delete this?.fd;
}
} catch (error) {
handleFileException(
export class MikroOrmStorage extends Storage {
private storageType: StorageType;
- private orm!: MikroORM | null;
+ private orm?: MikroORM;
constructor(storageUri: string, logPrefix: string, storageType: StorageType) {
super(storageUri, logPrefix);
try {
if (this?.orm) {
await this.orm.close();
- this.orm = null;
+ delete this?.orm;
}
} catch (error) {
this.handleDBError(this.storageType, error as Error);
import { Constants } from '../../utils';
export class MongoDBStorage extends Storage {
- private readonly client: MongoClient | null;
+ private readonly client?: MongoClient;
private connected: boolean;
constructor(storageUri: string, logPrefix: string) {
await this.client
?.db(this.dbName)
.collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE)
- .insertOne(performanceStatistics);
+ .replaceOne({ id: performanceStatistics.id }, performanceStatistics, { upsert: true });
} catch (error) {
this.handleDBError(StorageType.MONGO_DB, error as Error, Constants.PERFORMANCE_RECORDS_TABLE);
}