Skip to content

Deduplicate enums #1683

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
1 task done
imranbarbhuiya opened this issue May 27, 2024 · 6 comments
Open
1 task done

Deduplicate enums #1683

imranbarbhuiya opened this issue May 27, 2024 · 6 comments
Assignees
Labels
bug Something isn't working openapi-ts Relevant to the openapi-typescript library

Comments

@imranbarbhuiya
Copy link

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);
@imranbarbhuiya imranbarbhuiya added enhancement New feature or request PRs welcome PRs are welcome to solve this issue! openapi-ts Relevant to the openapi-typescript library labels May 27, 2024
@drwpow drwpow added the planned Expected in an upcoming version label Jun 19, 2024
@Amixx
Copy link

Amixx commented Jul 15, 2024

When is this planned? I need this feature, and am willing to try to implement it.

@Amixx
Copy link

Amixx commented Aug 1, 2024

@phk422 Thank you for implementing this feature! However, I found that it does not work - with this flag openapi-typescript command runs forever (and when the flag is removed it finished very quickly). Here is a minimal reproduction, please take a look: https://stackblitz.com/edit/vitejs-vite-8qzk9p?file=package.json
Try running npm run success and npm run infinite-loading and you will see the issue.

@imranbarbhuiya
Copy link
Author

imranbarbhuiya commented Aug 1, 2024

The problem with the current implementation is that the name of the enum isn't stable. I initially provided the diff but didn't implement it due to this issue. the issue is if we add a new route that references an enum from the existing routes and the current route is alphabetically above the previous route, the enum name will change and it'll require a new change in our code to change the enum name. Can we add a non-standard prop like x-enum-name and use that for the enum name if it exists to solve this issue? or if something similar already exists then let me know

cc: @phk422 @drwpow

@drwpow drwpow added bug Something isn't working and removed enhancement New feature or request PRs welcome PRs are welcome to solve this issue! planned Expected in an upcoming version labels Aug 1, 2024
@drwpow
Copy link
Contributor

drwpow commented Aug 1, 2024

Thanks for raising! In that case, I’ll keep this ticket open and just use this to track the bug now that the feature exists.

@phk422
Copy link
Contributor

phk422 commented Aug 2, 2024

@phk422 Thank you for implementing this feature! However, I found that it does not work - with this flag openapi-typescript command runs forever (and when the flag is removed it finished very quickly). Here is a minimal reproduction, please take a look: https://stackblitz.com/edit/vitejs-vite-8qzk9p?file=package.json Try running npm run success and npm run infinite-loading and you will see the issue.

This is indeed an issue. I suspect it's related to CLI argument parsing. I'll investigate if there's a way to resolve it. You can try placing other optional parameters at the end, like this:

openapi-typescript api/schema.yaml -o schema/schema.ts --enum --dedupe-enums

This should work correctly.

@darkbasic
Copy link

What about deduplicating enums sourced from different openapi definitions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working openapi-ts Relevant to the openapi-typescript library
Projects
None yet
Development

No branches or pull requests

6 participants