Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query string issue #2082

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

NikitaGuminsky
Copy link

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 '';

};

@mrlubos
Copy link
Collaborator

mrlubos commented Mar 20, 2024

@NikitaGuminsky will this not break existing implementations?

@NikitaGuminsky
Copy link
Author

@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.

@mrlubos
Copy link
Collaborator

mrlubos commented Mar 21, 2024

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

@NikitaGuminsky
Copy link
Author

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants