Skip to content

Commit 9d50bc7

Browse files
committed
Conditionally encode query parameters
1 parent d01adc9 commit 9d50bc7

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

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

+14-7
Original file line numberDiff line numberDiff line change
@@ -444,14 +444,21 @@ export async function generateApi(
444444

445445
const properties = parameters.map((param) => {
446446
const value = isFlatArg ? rootObject : accessProperty(rootObject, param.name);
447-
return createPropertyAssignment(
448-
param.originalName,
447+
448+
const encodedValue =
449449
encodeQueryParams && param.param?.in === 'query'
450-
? factory.createCallExpression(factory.createIdentifier('encodeURIComponent'), undefined, [
451-
factory.createCallExpression(factory.createIdentifier('String'), undefined, [value]),
452-
])
453-
: value
454-
);
450+
? factory.createConditionalExpression(
451+
value,
452+
undefined,
453+
factory.createCallExpression(factory.createIdentifier('encodeURIComponent'), undefined, [
454+
factory.createCallExpression(factory.createIdentifier('String'), undefined, [value]),
455+
]),
456+
undefined,
457+
factory.createIdentifier('undefined')
458+
)
459+
: value;
460+
461+
return createPropertyAssignment(param.originalName, encodedValue);
455462
});
456463

457464
return factory.createPropertyAssignment(

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

+5-2
Original file line numberDiff line numberDiff line change
@@ -235,12 +235,15 @@ describe('option encodeQueryParams', () => {
235235
encodeQueryParams: true,
236236
};
237237

238-
it('should encode query parameters', async () => {
238+
it('should conditionally encode query parameters', async () => {
239239
const api = await generateEndpoints({
240240
...config,
241241
filterEndpoints: ['findPetsByStatus'],
242242
});
243-
expect(api).toContain('status: encodeURIComponent(String(queryArg.status))');
243+
244+
expect(api).toMatch(
245+
/params:\s*{\s*\n\s*status:\s*queryArg\.status\s*\?\s*encodeURIComponent\(\s*String\(queryArg\.status\)\s*\)\s*:\s*undefined\s*,?\s*\n\s*}/s
246+
);
244247
});
245248

246249
it('should not encode path parameters', async () => {

0 commit comments

Comments
 (0)