Skip to content

Commit 788e243

Browse files
Merge pull request #675 from bitgopatmcl/deduplicate-enum-values
Deduplicate enum values when simplifying unions
2 parents 92573b6 + 3a8b8a8 commit 788e243

File tree

2 files changed

+28
-9
lines changed

2 files changed

+28
-9
lines changed

packages/openapi-generator/src/optimize.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,19 @@ export function simplifyUnion(schema: Schema, optimize: OptimizeFn): Schema {
4242

4343
const innerSchemas = schema.schemas.map(optimize);
4444

45-
const literals: Record<Primitive['type'], any[]> = {
46-
string: [],
47-
number: [],
48-
integer: [],
49-
boolean: [],
50-
null: [],
45+
const literals: Record<Primitive['type'], Set<any>> = {
46+
string: new Set(),
47+
number: new Set(),
48+
integer: new Set(),
49+
boolean: new Set(),
50+
null: new Set(),
5151
};
5252
const remainder: Schema[] = [];
5353
innerSchemas.forEach((innerSchema) => {
5454
if (isPrimitive(innerSchema) && innerSchema.enum !== undefined) {
55-
literals[innerSchema.type].push(...innerSchema.enum);
55+
innerSchema.enum.forEach((value) => {
56+
literals[innerSchema.type].add(value);
57+
});
5658
} else {
5759
remainder.push(innerSchema);
5860
}
@@ -62,8 +64,8 @@ export function simplifyUnion(schema: Schema, optimize: OptimizeFn): Schema {
6264
schemas: remainder,
6365
};
6466
for (const [key, value] of Object.entries(literals)) {
65-
if (value.length > 0) {
66-
result.schemas.push({ type: key as any, enum: value });
67+
if (value.size > 0) {
68+
result.schemas.push({ type: key as any, enum: Array.from(value) });
6769
}
6870
}
6971

packages/openapi-generator/test/optimize.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,20 @@ test('undefined property unions are simplified', () => {
9595

9696
assert.deepStrictEqual(optimize(input), expected);
9797
});
98+
99+
test('enums are deduplicated', () => {
100+
const input: Schema = {
101+
type: 'union',
102+
schemas: [
103+
{ type: 'string', enum: ['foo'] },
104+
{ type: 'string', enum: ['foo', 'bar'] },
105+
],
106+
};
107+
108+
const expected: Schema = {
109+
type: 'string',
110+
enum: ['foo', 'bar'],
111+
};
112+
113+
assert.deepStrictEqual(optimize(input), expected);
114+
});

0 commit comments

Comments
 (0)