-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.ts
82 lines (66 loc) · 2.47 KB
/
response.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import type { PlainObject } from './types.ts';
import { isPlainObject } from './util.ts';
// 2xx
export const OK = <T = PlainObject>(body: BodyInit | T, headers = {}) => {
const init = { status: 200, headers };
return isPlainObject<T>(body) || Array.isArray(body)
? Response.json(body, init)
: new Response(body, init);
};
export const Created = <T = PlainObject>(
body: BodyInit | T = '',
headers = {},
) => {
const init = { status: 201, headers };
return isPlainObject<T>(body) || Array.isArray(body)
? Response.json(body, init)
: new Response(body, init);
};
export const Accepted = (headers = {}) => new Response('', { status: 202, headers });
export const NoContent = (headers = {}) => new Response('', { status: 204, headers });
// 3xx
export const Redirect = (url: string, status = 302) => Response.redirect(url, status);
// 4xx
export const BadRequest = <T = PlainObject>(body: BodyInit | T = '') => {
const init = { status: 400 };
return isPlainObject<T>(body) || Array.isArray(body)
? Response.json(body, init)
: new Response(body, init);
};
export const Unauthorized = <T = PlainObject>(body: BodyInit | T = '') => {
const init = { status: 401 };
return isPlainObject<T>(body) || Array.isArray(body)
? Response.json(body, init)
: new Response(body, init);
};
export const Forbidden = <T = PlainObject>(body: BodyInit | T = '') => {
const init = { status: 403 };
return isPlainObject<T>(body) || Array.isArray(body)
? Response.json(body, init)
: new Response(body, init);
};
export const NotFound = (headers = {}) => new Response('Not Found', { status: 404, headers });
export const MethodNotAllowed = () => new Response('', { status: 405 });
export const NotAcceptable = () => new Response('', { status: 406 });
export const Conflict = <T = PlainObject>(body: BodyInit | T = '') => {
const init = { status: 409 };
return isPlainObject<T>(body) || Array.isArray(body)
? Response.json(body, init)
: new Response(body, init);
};
// 5xx
export const InternalServerError = <T = PlainObject>(
body: BodyInit | T = '',
) => {
const init = { status: 500 };
return isPlainObject<T>(body) || Array.isArray(body)
? Response.json(body, init)
: new Response(body, init);
};
// Special case (type-related)
export const HTML = (body: string | ReadableStream, headers = {}) =>
new Response(body, {
status: 200,
headers: { ...headers, 'Content-Type': 'text/html; charset=utf-8' },
});
export const Plain = (body?: BodyInit, init?: ResponseInit) => new Response(body, init);