Skip to content

Commit 774bf29

Browse files
authored
Merge pull request #6 from opennetwork/feature/json
Response.json + other helpers
2 parents e62d928 + 00b1fb3 commit 774bf29

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/response.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,61 @@ class Response extends Body {
7878
return response;
7979
}
8080

81+
static json(body: unknown, init?: ResponseInit) {
82+
const headers = new Headers(init?.headers);
83+
if (!headers.has("Content-Type")) {
84+
headers.set("Content-Type", "application/json");
85+
}
86+
return new Response(JSON.stringify(body), {
87+
...init,
88+
headers
89+
});
90+
}
91+
92+
static blob(body: Blob, init?: ResponseInit) {
93+
const headers = new Headers(init?.headers);
94+
if (!headers.has("Content-Type")) {
95+
headers.set("Content-Type", body.type ?? "application/octet-stream");
96+
}
97+
return new Response(body, {
98+
...init,
99+
headers
100+
});
101+
}
102+
103+
static arrayBuffer(body: ArrayBuffer | Buffer, init?: ResponseInit) {
104+
const headers = new Headers(init?.headers);
105+
if (!headers.has("Content-Type")) {
106+
headers.set("Content-Type", "application/octet-stream");
107+
}
108+
return new Response(body, {
109+
...init,
110+
headers
111+
});
112+
}
113+
114+
static text(body: string, init?: ResponseInit) {
115+
const headers = new Headers(init?.headers);
116+
if (!headers.has("Content-Type")) {
117+
headers.set("Content-Type", "text/plain");
118+
}
119+
return new Response(body, {
120+
...init,
121+
headers
122+
});
123+
}
124+
125+
static formData(body: FormData, init?: ResponseInit) {
126+
const headers = new Headers(init?.headers);
127+
if (!headers.has("Content-Type")) {
128+
headers.set("Content-Type", "multipart/form-data");
129+
}
130+
return new Response(body, {
131+
...init,
132+
headers
133+
});
134+
}
135+
81136
}
82137

83138
export { Response };

0 commit comments

Comments
 (0)