From fe791818e4bb6ae1e37e95c5528e7538c17ec8dd Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Mon, 29 Aug 2022 20:18:49 +0200 Subject: [PATCH] Add helper to serialize to JSON object with a map MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/performance/storage/JsonFileStorage.ts | 15 ++------------- src/utils/Utils.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 13 deletions(-) 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 + ); + } } -- 2.34.1