Skip to content

Commit 9ea74b6

Browse files
committed
feat: consolidate unions of t.unknown in generator
DX-644 This will consolidate t.unknowns when a well defined codec exists in the union, as it presents useless information in our specs and on dev-portal
1 parent dacc359 commit 9ea74b6

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

packages/openapi-generator/src/openapi.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,10 @@ export function schemaToOpenAPI(
102102
const nonUndefinedSchema = schema.schemas.find((s) => s.type !== 'undefined');
103103
// If nullSchema exists, that means that the union is also nullable
104104
const nullSchema = schema.schemas.find((s) => s.type === 'null');
105+
106+
// If any schema exists and it is in union with another schema - we can remove the any schema as an optimization
107+
const unknownSchema = schema.schemas.find((s) => s.type === 'any');
108+
105109
// and we can just return the other schema (while attaching the comment to that schema)
106110
const isOptional =
107111
schema.schemas.length >= 2 && undefinedSchema && nonUndefinedSchema;
@@ -113,6 +117,29 @@ export function schemaToOpenAPI(
113117
});
114118
}
115119

120+
// This is an edge case for something like this -> t.union([WellDefinedCodec, t.unknown])
121+
// It doesn't make sense to display the unknown codec in the OpenAPI spec so this essentially strips it out of the generation
122+
// so that we don't present useless information to the user
123+
const isUnionWithUnknown = schema.schemas.length >= 2 && unknownSchema;
124+
if (isUnionWithUnknown) {
125+
const nonUnknownSchemas = schema.schemas.filter((s) => s.type !== 'any');
126+
127+
if (nonUnknownSchemas.length === 1 && nonUnknownSchemas[0] !== undefined) {
128+
return schemaToOpenAPI({
129+
...nonUnknownSchemas[0],
130+
comment: schema.comment,
131+
...(nullSchema ? { nullable: true } : {}),
132+
});
133+
} else if (nonUnknownSchemas.length > 1) {
134+
return schemaToOpenAPI({
135+
type: 'union',
136+
schemas: nonUnknownSchemas,
137+
comment: schema.comment,
138+
...(nullSchema ? { nullable: true } : {}),
139+
});
140+
}
141+
}
142+
116143
for (const s of schema.schemas) {
117144
if (s.type === 'null') {
118145
nullable = true;

0 commit comments

Comments
 (0)