Skip to content

Commit ade18b1

Browse files
committed
fix: flattened optional type is optional
1 parent 213b5f4 commit ade18b1

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
@@ -324,7 +324,6 @@ export async function generateApi(
324324
const queryArgValues = Object.values(queryArg);
325325

326326
const isFlatArg = flattenArg && queryArgValues.length === 1;
327-
328327
const QueryArg = factory.createTypeReferenceNode(
329328
registerInterface(
330329
factory.createTypeAliasDeclaration(
@@ -333,7 +332,16 @@ export async function generateApi(
333332
undefined,
334333
queryArgValues.length > 0
335334
? isFlatArg
336-
? withQueryComment({ ...queryArgValues[0].type }, queryArgValues[0], false)
335+
? withQueryComment(
336+
factory.createUnionTypeNode([
337+
queryArgValues[0].type,
338+
...(!queryArgValues[0].required
339+
? [factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword)]
340+
: []),
341+
]),
342+
queryArgValues[0],
343+
false
344+
)
337345
: factory.createTypeLiteralNode(
338346
queryArgValues.map((def) =>
339347
withQueryComment(

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,22 @@ describe('option flattenArg', () => {
113113
});
114114
expect(api).toContain('queryArg.body');
115115
});
116+
117+
it('should flatten an optional arg as an optional type', async () => {
118+
const api = await generateEndpoints({
119+
...config,
120+
filterEndpoints: 'findPetsByTags',
121+
});
122+
expect(api).toMatch(/\| undefined/);
123+
});
124+
125+
it('should not flatten a non-optional arg with a superfluous union', async () => {
126+
const api = await generateEndpoints({
127+
...config,
128+
filterEndpoints: 'getPetById',
129+
});
130+
expect(api).not.toMatch(/^\s*\|/);
131+
});
116132
});
117133

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

0 commit comments

Comments
 (0)