From 05353b63d41b8337b1e9cff26cfe678d60b385da Mon Sep 17 00:00:00 2001 From: Matt Gibson Date: Thu, 17 Nov 2022 14:04:07 -0500 Subject: [PATCH] Make Record <-> Map idempotent Should we get in a situation where we _think_ an object has been jsonified, but hasn't been, we need to correctly deal with the object received to create our target. --- libs/common/spec/misc/utils.spec.ts | 13 +++++++++++++ libs/common/src/misc/utils.ts | 11 ++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/libs/common/spec/misc/utils.spec.ts b/libs/common/spec/misc/utils.spec.ts index b7c8c53c4f2..fb57c33fff1 100644 --- a/libs/common/spec/misc/utils.spec.ts +++ b/libs/common/spec/misc/utils.spec.ts @@ -268,6 +268,11 @@ describe("Utils Service", () => { expect(result).toEqual({ 1: "value1", 2: "value2" }); expect(Utils.recordToMap(result)).toEqual(map); }); + + it("should not convert an object if it's not a map", () => { + const obj = { key1: "value1", key2: "value2" }; + expect(Utils.mapToRecord(obj as any)).toEqual(obj); + }); }); describe("recordToMap", () => { @@ -295,5 +300,13 @@ describe("Utils Service", () => { ); expect(Utils.mapToRecord(result)).toEqual(record); }); + + it("should not convert an object if already a map", () => { + const map = new Map([ + ["key1", "value1"], + ["key2", "value2"], + ]); + expect(Utils.recordToMap(map as any)).toEqual(map); + }); }); }); diff --git a/libs/common/src/misc/utils.ts b/libs/common/src/misc/utils.ts index 0066ac8796c..ead692d6663 100644 --- a/libs/common/src/misc/utils.ts +++ b/libs/common/src/misc/utils.ts @@ -438,7 +438,13 @@ export class Utils { * @returns */ static mapToRecord(map: Map): Record { - return map == null ? null : Object.fromEntries(map); + if (map == null) { + return null; + } + if (!(map instanceof Map)) { + return map; + } + return Object.fromEntries(map); } /** @@ -452,7 +458,10 @@ export class Utils { static recordToMap(record: Record): Map { if (record == null) { return null; + } else if (record instanceof Map) { + return record; } + const entries = Object.entries(record); if (entries.length === 0) { return new Map();