openapi-typescript-codegen icon indicating copy to clipboard operation
openapi-typescript-codegen copied to clipboard

Query string issue

Open NikitaGuminsky opened this issue 1 year ago • 4 comments

The issue here stems from how the getQueryString function processes arrays. When you pass an array with a single item, it doesn't append the [] to the parameter name, which is needed by many back-end frameworks to recognize the parameter as an array.

To fix this issue, you need to modify the process function so that it always appends [] to the parameter name when the value is an array, regardless of its length. Here's the modified version of your getQueryString function:

export const getQueryString = (params: Record<string, any>): string => { const qs: string[] = [];

const append = (key: string, value: any) => {
	qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
};

const process = (key: string, value: any) => {
	if (isDefined(value)) {
		if (Array.isArray(value)) {
			value.forEach(v => {
				process(`${key}[]`, v);
			});
		} else if (typeof value === 'object') {
			Object.entries(value).forEach(([k, v]) => {
				process(`${key}[${k}]`, v);
			});
		} else {
			append(key, value);
		}
	}
};

Object.entries(params).forEach(([key, value]) => {
	process(key, value);
});

if (qs.length > 0) {
	return `?${qs.join('&')}`;
}

return '';

};

NikitaGuminsky avatar Mar 20 '24 17:03 NikitaGuminsky

@NikitaGuminsky will this not break existing implementations?

mrlubos avatar Mar 20 '24 19:03 mrlubos

@NikitaGuminsky will this not break existing implementations?

No, this doesn't break anything. If you use pure axios, it also passes request parameters in this format, which are arrays. Almost all server applications accept them in this form.

NikitaGuminsky avatar Mar 21 '24 08:03 NikitaGuminsky

@NikitaGuminsky which server application doesn't accept the current version?

mrlubos avatar Mar 21 '24 08:03 mrlubos

@NikitaGuminsky which server application doesn't accept the current version?

In our case we are using nestjs. normally we set validations on parameters. If we set a validation to accept arrays, we get an error when receiving a string.

NikitaGuminsky avatar Mar 21 '24 09:03 NikitaGuminsky