Skip to content

Deduplicate enums #1683

Open
Open
@imranbarbhuiya

Description

@imranbarbhuiya

Description
Hi, when using the --enum flag, the same enum gets generated multiple times if it's used multiple times, can we get a new flag or something to not generate duplicate enums when the keys and values of the enum match an existing enum?

Proposal
A new flag that dedupes the enums will be useful. Currently, I'm patching the lib and keeping the stringified version of keys-values in a map and checking if it exists then returning instead of creating a new enum. I can create a PR to implement this feature first creating this issue to discuss how we can proceed with the naming and all

Checklist

My diff
diff --git a/dist/lib/ts.js b/dist/lib/ts.js
index 12edcb37af95c3f1f73fafac145d27aba44571b3..2af43b8a46e80c09c1cf38ea0fb8d23b23f47390 100644
--- a/dist/lib/ts.js
+++ b/dist/lib/ts.js
@@ -111,10 +111,15 @@ export function tsDedupe(types) {
     }
     return filteredTypes;
 }
+const visited = new Map();
 export function tsEnum(name, members, metadata, options) {
     let enumName = sanitizeMemberName(name);
     enumName = `${enumName[0].toUpperCase()}${enumName.substring(1)}`;
-    return ts.factory.createEnumDeclaration(options ? tsModifiers({ export: options.export ?? false }) : undefined, enumName, members.map((value, i) => tsEnumMember(value, metadata?.[i])));
+    const hash = `${members.map((v, i) => `${metadata?.[i]?.name ?? String(v)}:${metadata?.[i]?.description ?? ""}`).join(",")}`;
+    if(visited.has(hash)) return visited.get(hash);
+    const data = ts.factory.createEnumDeclaration(options ? tsModifiers({ export: options.export ?? false }) : undefined, enumName, members.map((value, i) => tsEnumMember(value, metadata?.[i])));
+    visited.set(hash, data);
+    return data;
 }
 export function tsArrayLiteralExpression(name, elementType, values, options) {
     let variableName = sanitizeMemberName(name);
diff --git a/dist/transform/schema-object.js b/dist/transform/schema-object.js
index 0ae8a4223850fd722e0e99db34e2c6e09cfe880e..ccfc6041488e78a5925fc15546db76d86bd83802 100644
--- a/dist/transform/schema-object.js
+++ b/dist/transform/schema-object.js
@@ -42,7 +42,7 @@ export function transformSchemaObjectWithComposition(schemaObject, options) {
             const enumType = tsEnum(enumName, schemaObject.enum, metadata, {
                 export: true,
             });
-            options.ctx.injectFooter.push(enumType);
+            if(!options.ctx.injectFooter.includes(enumType)) options.ctx.injectFooter.push(enumType);
             return ts.factory.createTypeReferenceNode(enumType.name);
         }
         const enumType = schemaObject.enum.map(tsLiteral);

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingopenapi-tsRelevant to the openapi-typescript library

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions