Skip to content

Response.json + other helpers #6

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

Merged
merged 3 commits into from
May 18, 2022
Merged
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
55 changes: 55 additions & 0 deletions src/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,61 @@ class Response extends Body {
return response;
}

static json(body: unknown, init?: ResponseInit) {
const headers = new Headers(init?.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
return new Response(JSON.stringify(body), {
...init,
headers
});
}

static blob(body: Blob, init?: ResponseInit) {
const headers = new Headers(init?.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", body.type ?? "application/octet-stream");
}
return new Response(body, {
...init,
headers
});
}

static arrayBuffer(body: ArrayBuffer | Buffer, init?: ResponseInit) {
const headers = new Headers(init?.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/octet-stream");
}
return new Response(body, {
...init,
headers
});
}

static text(body: string, init?: ResponseInit) {
const headers = new Headers(init?.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "text/plain");
}
return new Response(body, {
...init,
headers
});
}

static formData(body: FormData, init?: ResponseInit) {
const headers = new Headers(init?.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "multipart/form-data");
}
return new Response(body, {
...init,
headers
});
}

}

export { Response };