forked from sholladay/pogo
/
response.ts
101 lines (98 loc) · 3.09 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { cookie, status } from '../dependencies.ts';
import { Bang } from './bang.ts';
import { ResponseBody } from './types.ts';
interface ResponseOptions {
body?: ResponseBody,
headers?: HeadersInit,
status?: number
};
interface CookieOptions extends Omit<cookie.Cookie, 'name'> {
name?: cookie.Cookie['name']
}
export default class Response {
body: ResponseBody;
headers: Headers;
status: number;
permanent?: () => this;
temporary?: () => this;
rewritable?: (isRewritable: boolean) => this;
constructor(options?: ResponseOptions) {
this.body = options?.body ?? null;
this.headers = new Headers(options?.headers);
this.status = options?.status ?? status.OK;
}
static wrap(input: Response | ResponseBody | Error) {
if (input instanceof Response) {
return input;
}
if (input instanceof Error) {
return Bang.wrap(input).response;
}
return new Response({ body : input });
}
code(statusCode: number) {
this.status = statusCode;
return this;
}
created(url?: string) {
this.code(status.Created);
if (url) {
this.location(url);
}
return this;
}
header(name: string, value: string) {
this.headers.set(name, value);
return this;
}
location(url: string) {
return this.header('Location', url);
}
redirect(url: string) {
const _isRewritable = () => {
return [status.MovedPermanently, status.Found].includes(this.status);
};
const _isTemporary = () => {
return [status.TemporaryRedirect, status.Found].includes(this.status);
};
this.code(status.Found);
this.location(url);
this.permanent = () => {
this.code(_isRewritable() ? status.MovedPermanently : status.PermanentRedirect);
return this;
};
this.temporary = () => {
this.code(_isRewritable() ? status.Found : status.TemporaryRedirect);
return this;
};
this.rewritable = (isRewritable?: boolean) => {
if (isRewritable === false) {
this.code(_isTemporary() ? status.TemporaryRedirect : status.PermanentRedirect);
}
else {
this.code(_isTemporary() ? status.Found : status.MovedPermanently);
}
return this;
};
return this;
}
state(name: cookie.Cookie): this;
state(name: string, value: string | CookieOptions): this;
state(name: string | cookie.Cookie, value?: string | CookieOptions) {
cookie.setCookie(this, {
httpOnly : true,
sameSite : 'Strict',
secure : true,
...(typeof name === 'object' ? name : { name }),
...(typeof value === 'object' ? value : { value: value ?? '' })
});
return this;
}
type(mediaType: string) {
return this.header('Content-Type', mediaType);
}
unstate(name: string) {
cookie.deleteCookie(this, name);
return this;
}
}