-
-
Notifications
You must be signed in to change notification settings - Fork 429
/
context.ts
191 lines (167 loc) · 5.95 KB
/
context.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono.ts'
import type { CookieOptions } from './utils/cookie.ts'
import { serialize } from './utils/cookie.ts'
import type { StatusCode } from './utils/http-status.ts'
import { isAbsoluteURL } from './utils/url.ts'
type Headers = Record<string, string>
export type Data = string | ArrayBuffer | ReadableStream
export interface Context<
RequestParamKeyType extends string = string,
E extends Partial<Environment> = any
> {
req: Request<RequestParamKeyType>
env: E['Bindings']
event: FetchEvent
executionCtx: ExecutionContext
finalized: boolean
get res(): Response
set res(_res: Response)
header: (name: string, value: string) => void
status: (status: StatusCode) => void
set: {
<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void
<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void
(key: string, value: any): void
}
get: {
<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]
<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]
<T = any>(key: string): T
}
pretty: (prettyJSON: boolean, space?: number) => void
newResponse: (data: Data | null, status: StatusCode, headers: Headers) => Response
body: (data: Data | null, status?: StatusCode, headers?: Headers) => Response
text: (text: string, status?: StatusCode, headers?: Headers) => Response
json: <T>(object: T, status?: StatusCode, headers?: Headers) => Response
html: (html: string, status?: StatusCode, headers?: Headers) => Response
redirect: (location: string, status?: StatusCode) => Response
cookie: (name: string, value: string, options?: CookieOptions) => void
notFound: () => Response | Promise<Response>
}
export class HonoContext<
RequestParamKeyType extends string = string,
E extends Partial<Environment> = Environment
> implements Context<RequestParamKeyType, E>
{
req: Request<RequestParamKeyType>
env: E['Bindings']
finalized: boolean
_status: StatusCode = 200
private _executionCtx: FetchEvent | ExecutionContext | undefined
private _pretty: boolean = false
private _prettySpace: number = 2
private _map: Record<string, any> | undefined
private _headers: Record<string, string> | undefined
private _res: Response | undefined
private notFoundHandler: NotFoundHandler
constructor(
req: Request,
env: E['Bindings'] | undefined = undefined,
executionCtx: FetchEvent | ExecutionContext | undefined = undefined,
notFoundHandler: NotFoundHandler = () => new Response()
) {
this._executionCtx = executionCtx
this.req = req
this.env = env || ({} as Bindings)
this.notFoundHandler = notFoundHandler
this.finalized = false
}
get event(): FetchEvent {
if (this._executionCtx instanceof FetchEvent) {
return this._executionCtx
} else {
throw Error('This context has no FetchEvent')
}
}
get executionCtx(): ExecutionContext {
if (this._executionCtx) {
return this._executionCtx
} else {
throw Error('This context has no ExecutionContext')
}
}
get res(): Response {
return (this._res ||= new Response())
}
set res(_res: Response) {
this._res = _res
this.finalized = true
}
header(name: string, value: string): void {
this._headers ||= {}
this._headers[name.toLowerCase()] = value
if (this.finalized) {
this.res.headers.set(name, value)
}
}
status(status: StatusCode): void {
this._status = status
}
set<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void
set<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void
set(key: string, value: any): void
set(key: string, value: any): void {
this._map ||= {}
this._map[key] = value
}
get<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]
get<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]
get<T = any>(key: string): T
get(key: string) {
if (!this._map) {
return undefined
}
return this._map[key]
}
pretty(prettyJSON: boolean, space: number = 2): void {
this._pretty = prettyJSON
this._prettySpace = space
}
newResponse(data: Data | null, status: StatusCode, headers: Headers = {}): Response {
const _headers = { ...this._headers }
if (this._res) {
this._res.headers.forEach((v, k) => {
_headers[k] = v
})
}
return new Response(data, {
status: status || this._status || 200,
headers: { ..._headers, ...headers },
})
}
body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {
return this.newResponse(data, status, headers)
}
text(text: string, status: StatusCode = this._status, headers: Headers = {}): Response {
headers['content-type'] = 'text/plain; charset=UTF-8'
return this.body(text, status, headers)
}
json<T>(object: T, status: StatusCode = this._status, headers: Headers = {}): Response {
const body = this._pretty
? JSON.stringify(object, null, this._prettySpace)
: JSON.stringify(object)
headers['content-type'] = 'application/json; charset=UTF-8'
return this.body(body, status, headers)
}
html(html: string, status: StatusCode = this._status, headers: Headers = {}): Response {
headers['content-type'] = 'text/html; charset=UTF-8'
return this.body(html, status, headers)
}
redirect(location: string, status: StatusCode = 302): Response {
if (!isAbsoluteURL(location)) {
const url = new URL(this.req.url)
url.pathname = location
location = url.toString()
}
return this.newResponse(null, status, {
Location: location,
})
}
cookie(name: string, value: string, opt?: CookieOptions): void {
const cookie = serialize(name, value, opt)
this.header('set-cookie', cookie)
}
notFound(): Response | Promise<Response> {
return this.notFoundHandler(this as any)
}
}