Skip to content

Commit 5dbffa3

Browse files
jbl428imdudu1
andcommitted
feat: implement payload builder
Co-authored-by: imdudu1 <[email protected]>
1 parent 9315524 commit 5dbffa3

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

lib/utils/payload-builder.ts

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import { TupleArrayBuilder } from "./tuple-array-builder";
2+
import {
3+
type RequestBodyMetadata,
4+
type RequestFormMetadata,
5+
} from "../decorators";
6+
7+
export class PayloadBuilder {
8+
constructor(
9+
private readonly args: any[],
10+
private readonly metadata: {
11+
body?: RequestBodyMetadata;
12+
form?: RequestFormMetadata;
13+
} = {}
14+
) {}
15+
16+
contentType(): string | undefined {
17+
if (this.metadata.form !== undefined) {
18+
return "application/x-www-form-urlencoded";
19+
}
20+
21+
if (this.metadata.body !== undefined) {
22+
return "application/json";
23+
}
24+
25+
return undefined;
26+
}
27+
28+
build(): BodyInit | undefined {
29+
if (this.metadata.form !== undefined) {
30+
const form = new FormData();
31+
this.data.forEach(([index, value]) => {
32+
if (value !== undefined) {
33+
form.append(value, this.args[index]);
34+
return;
35+
}
36+
37+
TupleArrayBuilder.of<string, string | Blob>(this.args[index]).forEach(
38+
([k, v]) => {
39+
form.append(k, v);
40+
}
41+
);
42+
});
43+
44+
return form;
45+
}
46+
47+
if (this.metadata.body !== undefined) {
48+
const payload = this.data.reduce(
49+
(
50+
acc: Record<string, unknown>,
51+
[index, value]: [number, string | undefined]
52+
) => this.makePayload(acc, index, value),
53+
{}
54+
);
55+
56+
return JSON.stringify(payload);
57+
}
58+
59+
return undefined;
60+
}
61+
62+
private makePayload(
63+
acc: Record<string, unknown>,
64+
index: number,
65+
value?: string
66+
): Record<string, unknown> {
67+
if (value !== undefined) {
68+
acc[value] = this.args[index];
69+
return acc;
70+
}
71+
72+
TupleArrayBuilder.of<string, unknown>(this.args[index]).forEach(
73+
([k, v]) => {
74+
acc[k] = v;
75+
}
76+
);
77+
78+
return acc;
79+
}
80+
81+
private get data(): Array<[number, string | undefined]> {
82+
if (this.metadata.form !== undefined) {
83+
return this.metadata.form.toArray();
84+
}
85+
86+
if (this.metadata.body !== undefined) {
87+
return this.metadata.body.toArray();
88+
}
89+
90+
return [];
91+
}
92+
}

0 commit comments

Comments
 (0)