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

Generate url with nested query params #175

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 37 additions & 22 deletions lib/route-recognizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ function recognizeChar<THandler>(
}

export interface QueryParams {
[param: string]: string[] | string | null | undefined;
[param: string]: Record<string, any> | string[] | string | null | undefined;
}

export interface Result<THandler> {
Expand Down Expand Up @@ -688,32 +688,47 @@ class RouteRecognizer<THandler = string> {
}

generateQueryString(params: Params): string {
const pairs: string[] = [];
const keys: string[] = Object.keys(params);
keys.sort();
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = params[key];
if (value == null) {
continue;
const reducer = (obj: Params, parentPrefix: string | null = null) => (prev: string[], key: string) => {
const val = obj[key];
if (val === null || val === undefined) {
return prev;
}
let pair = encodeURIComponent(key);
if (isArray(value)) {
for (let j = 0; j < value.length; j++) {
const arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
} else {
pair += "=" + encodeURIComponent(value as string);
pairs.push(pair);

const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;

if (val == null || typeof val === 'function') {
prev.push(`${prefix}=`);
return prev;
}
}

if (isArray(val)) {
for (let j = 0; j < val.length; j++) {
// handle array query params. array format brackets. (Other options are indices a[0]=b&a[1]=c or repeat a=b&a=c)
if (['string', 'number', 'boolean'].includes(typeof val[j])) {
const arrayPair = key + "[]" + "=" + encodeURIComponent(val[j]);
prev.push(arrayPair);
} else {
prev.push(Object.keys(val[j] as Params).sort().reduce(reducer(val[j] as Params, prefix + `[${j}]`), []).join('&'));
}
}

if (pairs.length === 0) {
return "";
return prev;
} else if (['string', 'number', 'boolean'].includes(typeof val)) {
prev.push(`${prefix}=${encodeURIComponent(val as string)}`);
return prev;
}

prev.push(Object.keys(val as Params).sort().reduce(reducer(val as Params, parentPrefix ? prefix : `${prefix}=`), []).join('&'));
return prev;
};

const sortedKeys = Object.keys(params).sort();
// avoid appending unnecessary '?'
if (!sortedKeys.length || sortedKeys.every((k) => params[k] === undefined || params[k] === null)) {
return '';
}

return "?" + pairs.join("&");
return '?' + sortedKeys.reduce(reducer(params), []).join('&');
}

parseQueryString(queryString: string): QueryParams {
Expand Down
31 changes: 30 additions & 1 deletion tests/recognizer-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,23 @@ QUnit.test(
}
);

QUnit.test("Deserialize query param nested object", (assert: Assert) => {
const handler = {};
const router = new RouteRecognizer<{}>();
router.add([{ path: "/foo/bar", handler }]);

const results = queryParams(router.recognize("/foo/bar?filter=[user][name][$contains]=nick"));
assert.deepEqual(results, {
filter: {
user: {
name: {
$contains: 'nick'
}
}
}
});
});

QUnit.test("Multiple `/` routes recognize", (assert: Assert) => {
const handler1 = { handler: 1 };
const handler2 = { handler: 2 };
Expand Down Expand Up @@ -1629,7 +1646,7 @@ QUnit.module("Route Generation", hooks => {
QUnit.test(
"Parsing and generation results into the same input string",
(assert: Assert) => {
const query = "filter%20data=date";
const query = "filter data=date";
assert.equal(
router.generateQueryString(router.parseQueryString(query)),
"?" + query
Expand Down Expand Up @@ -1721,6 +1738,18 @@ QUnit.module("Route Generation", hooks => {
router.generate("index", { queryParams: { filter: "date", sort: 0 } }),
"/?filter=date&sort=0"
);
assert.equal(
router.generate("index", { queryParams: { filter: { age: 10, user: { name: { $contains: 'scoot' } } }, sort: 0 } }),
"/?filter=[age]=10&filter=[user][name][$contains]=scoot&sort=0"
);
assert.equal(
router.generate("index", { queryParams: { sort: 0, filter: { age: 0, user: { name: { $contains: 'scoot' } } } } }),
"/?filter=[age]=0&filter=[user][name][$contains]=scoot&sort=0"
);
assert.equal(
router.generate("index", { queryParams: { sort: 0, filter: { name: 'bike', children: [{ name: { $contains: 'scoot' } }, { name: { $contains: 'er' }}] } }, sort: 0 }),
"/?filter=[children][0][name][$contains]=scoot&filter=[children][1][name][$contains]=er&filter=[name]=bike&sort=0"
);
});

QUnit.test("Generation works with array query params", (assert: Assert) => {
Expand Down