From: Jérôme Benoit Date: Mon, 29 Aug 2022 18:18:49 +0000 (+0200) Subject: Add helper to serialize to JSON object with a map X-Git-Tag: v1.1.69~20 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=fe791818e4bb6ae1e37e95c5528e7538c17ec8dd;p=e-mobility-charging-stations-simulator.git Add helper to serialize to JSON object with a map Signed-off-by: Jérôme Benoit --- diff --git a/src/performance/storage/JsonFileStorage.ts b/src/performance/storage/JsonFileStorage.ts index d1c294d8..2cdab505 100644 --- a/src/performance/storage/JsonFileStorage.ts +++ b/src/performance/storage/JsonFileStorage.ts @@ -7,6 +7,7 @@ import lockfile from 'proper-lockfile'; import { FileType } from '../../types/FileType'; import type Statistics from '../../types/Statistics'; import FileUtils from '../../utils/FileUtils'; +import Utils from '../../utils/Utils'; import { Storage } from './Storage'; export class JsonFileStorage extends Storage { @@ -30,19 +31,7 @@ export class JsonFileStorage extends Storage { performanceRecords.push(performanceStatistics); fs.writeFileSync( this.dbName, - JSON.stringify( - performanceRecords, - (key, value) => { - if (value instanceof Map) { - return { - dataType: 'Map', - value: [...value], - }; - } - return value as Statistics; - }, - 2 - ), + Utils.JSONStringifyWithMapSupport(performanceRecords, 2), 'utf8' ); } catch (error) { diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 1ad1a792..5b66368f 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -238,4 +238,23 @@ export default class Utils { public static secureRandom(): number { return crypto.randomBytes(4).readUInt32LE() / 0x100000000; } + + public static JSONStringifyWithMapSupport( + obj: Record | Record[], + space?: number + ): string { + return JSON.stringify( + obj, + (key, value: Record) => { + if (value instanceof Map) { + return { + dataType: 'Map', + value: [...value], + }; + } + return value; + }, + space + ); + } }