From 11cab93ae11e3a3408b06e4aece5d63f30cd4a0d Mon Sep 17 00:00:00 2001 From: Tomas Dvorak Date: Wed, 2 Oct 2024 12:11:27 +0200 Subject: [PATCH] feat(serializer): supports serialization for class with the same name --- src/serializer/utils.ts | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/src/serializer/utils.ts b/src/serializer/utils.ts index e240b37b..15898dc5 100644 --- a/src/serializer/utils.ts +++ b/src/serializer/utils.ts @@ -82,15 +82,32 @@ export function isRootNode(data: unknown): data is RootNode { ); } -export function extractClassName(value: unknown): string { - if (R.isObjectType(value) && "constructor" in value) { - return value.constructor.name; - } - if (R.isFunction(value)) { - return value.name || value.constructor?.name || Function.name; - } - return extractClassName(primitiveToSerializableClass(value)); -} +export const extractClassName = (() => { + const registry = new Map(); + const register = (name: string, factory: any) => { + if (!registry.has(name)) { + registry.set(name, []); + } + const target = registry.get(name)!; + let index = target.indexOf(factory); + if (index === -1) { + index = target.push(factory) - 1; + } + return [name, index].filter(Boolean).join(""); + }; + + return (value: unknown): string => { + if (R.isObjectType(value) && "constructor" in value) { + const name = value.constructor.name; + return register(name, value.constructor); + } + if (R.isFunction(value)) { + const name = value.name || value.constructor?.name || Function.name; + return register(name, value); + } + return extractClassName(primitiveToSerializableClass(value)); + }; +})(); const ClassByValueType = { string: String,