Skip to content

Commit 3419174

Browse files
committed
refactor: replace UrlSearchParam to querystring module
1 parent fa6ddb5 commit 3419174

File tree

2 files changed

+58
-13
lines changed

2 files changed

+58
-13
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { describe, it, expect } from "vitest";
2+
import { RequestParamBuilder } from "./request-param.builder";
3+
4+
describe("RequestParamBuilder", () => {
5+
it("should build query string with explicit key", () => {
6+
// given
7+
const builder = new RequestParamBuilder(0, "keyword");
8+
const args = ["search"];
9+
10+
// when
11+
const actual = builder.build(args);
12+
13+
// then
14+
expect(actual).toBe("?keyword=search");
15+
});
16+
17+
it("should build query string without key", () => {
18+
// given
19+
const builder = new RequestParamBuilder(1);
20+
const args = ["invalid", { foo: "bar" }];
21+
22+
// when
23+
const actual = builder.build(args);
24+
25+
// then
26+
expect(actual).toBe("?foo=bar");
27+
});
28+
29+
it("should encode query string", () => {
30+
// given
31+
const builder = new RequestParamBuilder(0, "keyword");
32+
const args = ["?@#$%^&+ "];
33+
34+
// when
35+
const actual = builder.build(args);
36+
37+
// then
38+
expect(actual).toBe("?keyword=%3F%40%23%24%25%5E%26%2B%20");
39+
});
40+
});

lib/builders/request-param.builder.ts

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import querystring from "node:querystring";
12
import { TupleArrayBuilder } from "./tuple-array.builder";
23

34
export class RequestParamBuilder {
@@ -20,20 +21,24 @@ export class RequestParamBuilder {
2021
return "";
2122
}
2223

23-
const searchParams = new URLSearchParams();
24-
this.metadata.forEach(([index, key]) => {
25-
if (key != null) {
26-
searchParams.set(key, args[index]);
27-
return;
28-
}
29-
30-
TupleArrayBuilder.of<string, unknown>(args[index]).forEach(
31-
([key, value]) => {
32-
searchParams.set(key, `${value?.toString() ?? ""}`);
24+
const result = this.metadata.reduce<Record<string, any>>(
25+
(acc, [index, key]) => {
26+
if (key != null) {
27+
acc[key] = args[index];
28+
return acc;
3329
}
34-
);
35-
});
3630

37-
return "?" + searchParams.toString();
31+
TupleArrayBuilder.of<string, unknown>(args[index]).forEach(
32+
([key, value]) => {
33+
acc[key] = value;
34+
}
35+
);
36+
37+
return acc;
38+
},
39+
{}
40+
);
41+
42+
return "?" + querystring.stringify(result);
3843
}
3944
}

0 commit comments

Comments
 (0)