Skip to content

Commit cd42073

Browse files
authored
Merge pull request #4317 from sebws/fix/openapi-codegen-flatten-optional
2 parents 79c413d + ade18b1 commit cd42073

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

packages/rtk-query-codegen-openapi/src/generate.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,6 @@ export async function generateApi(
331331
const queryArgValues = Object.values(queryArg);
332332

333333
const isFlatArg = flattenArg && queryArgValues.length === 1;
334-
335334
const QueryArg = factory.createTypeReferenceNode(
336335
registerInterface(
337336
factory.createTypeAliasDeclaration(
@@ -340,7 +339,16 @@ export async function generateApi(
340339
undefined,
341340
queryArgValues.length > 0
342341
? isFlatArg
343-
? withQueryComment({ ...queryArgValues[0].type }, queryArgValues[0], false)
342+
? withQueryComment(
343+
factory.createUnionTypeNode([
344+
queryArgValues[0].type,
345+
...(!queryArgValues[0].required
346+
? [factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword)]
347+
: []),
348+
]),
349+
queryArgValues[0],
350+
false
351+
)
344352
: factory.createTypeLiteralNode(
345353
queryArgValues.map((def) =>
346354
withQueryComment(

packages/rtk-query-codegen-openapi/test/generateEndpoints.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,22 @@ describe('option flattenArg', () => {
181181
});
182182
expect(api).toContain('queryArg.body');
183183
});
184+
185+
it('should flatten an optional arg as an optional type', async () => {
186+
const api = await generateEndpoints({
187+
...config,
188+
filterEndpoints: 'findPetsByTags',
189+
});
190+
expect(api).toMatch(/\| undefined/);
191+
});
192+
193+
it('should not flatten a non-optional arg with a superfluous union', async () => {
194+
const api = await generateEndpoints({
195+
...config,
196+
filterEndpoints: 'getPetById',
197+
});
198+
expect(api).not.toMatch(/^\s*\|/);
199+
});
184200
});
185201

186202
test('hooks generation', async () => {

0 commit comments

Comments
 (0)