Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions packages/openapi-generator/src/optimize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,19 @@ export function simplifyUnion(schema: Schema, optimize: OptimizeFn): Schema {

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

const literals: Record<Primitive['type'], any[]> = {
string: [],
number: [],
integer: [],
boolean: [],
null: [],
const literals: Record<Primitive['type'], Set<any>> = {
string: new Set(),
number: new Set(),
integer: new Set(),
boolean: new Set(),
null: new Set(),
};
const remainder: Schema[] = [];
innerSchemas.forEach((innerSchema) => {
if (isPrimitive(innerSchema) && innerSchema.enum !== undefined) {
literals[innerSchema.type].push(...innerSchema.enum);
innerSchema.enum.forEach((value) => {
literals[innerSchema.type].add(value);
});
} else {
remainder.push(innerSchema);
}
Expand All @@ -62,8 +64,8 @@ export function simplifyUnion(schema: Schema, optimize: OptimizeFn): Schema {
schemas: remainder,
};
for (const [key, value] of Object.entries(literals)) {
if (value.length > 0) {
result.schemas.push({ type: key as any, enum: value });
if (value.size > 0) {
result.schemas.push({ type: key as any, enum: Array.from(value) });
}
}

Expand Down
17 changes: 17 additions & 0 deletions packages/openapi-generator/test/optimize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,20 @@ test('undefined property unions are simplified', () => {

assert.deepStrictEqual(optimize(input), expected);
});

test('enums are deduplicated', () => {
const input: Schema = {
type: 'union',
schemas: [
{ type: 'string', enum: ['foo'] },
{ type: 'string', enum: ['foo', 'bar'] },
],
};

const expected: Schema = {
type: 'string',
enum: ['foo', 'bar'],
};

assert.deepStrictEqual(optimize(input), expected);
});