This repository has been archived by the owner on Jun 27, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.ts
294 lines (257 loc) · 6.29 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2023 Samuel Kopp. All rights reserved. Apache-2.0 license.
/// <reference types='./env.d.ts' />
import { encode } from 'std/encoding/base64.ts'
import { ZodType } from 'zod'
import { AppContext } from './cheetah.ts'
import { ObjectType, Payload } from './handler.ts'
import { RequestContext } from './request_context.ts'
import { ResponseContext } from './response_context.ts'
const HTTP_MESSAGES = {
'Bad Request': 400,
'Unauthorized': 401,
'Access Denied': 403,
'Not Found': 404,
'Method Not Allowed': 405,
'Not Acceptable': 406,
'Request Timeout': 408,
'Conflict': 409,
'Gone': 410,
'Length Required': 411,
'Precondition Failed': 412,
'Content Too Large': 413,
'URI Too Long': 414,
'Unsupported Media Type': 415,
'Range Not Satisfiable': 416,
'Expectation Failed': 417,
'Teapot': 418,
'Misdirected': 421,
'Upgrade Required': 426,
'Precondition Required': 428,
'Rate Limit Exceeded': 429,
'Regional Ban': 451,
'Something Went Wrong': 500,
}
export class Context<
Params extends Record<string, unknown> = Record<string, unknown>,
ValidatedBody extends ZodType = never,
ValidatedCookies extends ObjectType = never,
ValidatedHeaders extends ObjectType = never,
ValidatedQuery extends ObjectType = never,
> {
#a
#c: Cache | undefined
#i
#p
#r
#s
#req:
| RequestContext<
Params,
ValidatedBody,
ValidatedCookies,
ValidatedHeaders,
ValidatedQuery
>
| undefined
#res: ResponseContext | undefined
/**
* Wait until the response is sent to the client, then resolve the promise.
*/
waitUntil: (promise: Promise<unknown>) => void
constructor(
__app: AppContext,
__internal: {
b: Exclude<Payload, void> | null
c: number
h: Headers
},
p: Record<string, string | undefined>,
r: Request,
s: {
body?: ZodType | undefined
cookies?: ObjectType | undefined
headers?: ObjectType | undefined
query?: ObjectType | undefined
[key: string]: unknown
} | null,
waitUntil: (promise: Promise<unknown>) => void,
) {
this.#a = __app
this.#i = __internal
this.#p = p
this.#r = r
this.#s = s
this.waitUntil = waitUntil
}
get __app(): AppContext {
return this.#a
}
get cache(): Cache {
if (this.#c) {
return this.#c
}
this.#c = new Cache(this)
return this.#c
}
get dev(): boolean {
return this.#a.debugging ||
this.runtime === 'deno' && Deno.env.get('DEV') === 'true'
}
env<T extends keyof Variables>(name: T): Variables[T] {
return this.runtime === 'deno'
? Deno.env.get(name)
: (this.#a.env as Variables)[name]
}
get req(): RequestContext<
Params,
ValidatedBody,
ValidatedCookies,
ValidatedHeaders,
ValidatedQuery
> {
if (this.#req) {
return this.#req
}
this.#req = new RequestContext(
this.#a,
this.#p,
this.#r,
this.#s,
this.exception,
)
return this.#req
}
get res(): ResponseContext {
if (this.#res) {
return this.#res
}
this.#res = new ResponseContext(this.#i)
return this.#res
}
get runtime() {
return this.#a.runtime
}
exception(error: keyof typeof HTTP_MESSAGES, description?: string) {
const code = HTTP_MESSAGES[error]
return new Exception(error, description, code)
}
}
/** @private */
export class Exception {
public response
constructor(
error: string,
description: string | undefined,
code: number,
) {
this.response = (request: Request) => {
const a = request.headers.get('accept')
const json = a
? a.indexOf('application/json') > -1 ||
a.indexOf('*/*') > -1
: false
return new Response(
json ? JSON.stringify({ error, description, code }) : error,
{
headers: {
'content-type': `${
json ? 'application/json' : 'text/plain'
}; charset=utf-8;`,
},
status: code,
},
)
}
}
}
class Cache {
#cache: globalThis.Cache | null
#context
#name
constructor(c: Context) {
this.#cache = null
this.#context = c
this.#name = c.__app.caching?.name ?? 'cheetah'
}
async set(
key: string,
value: string | Record<string, unknown> | Uint8Array,
options?: {
maxAge?: number
},
) {
if (this.#cache === null) {
this.#cache = await caches.open(this.#name)
}
this.#context.waitUntil(
this.#cache.put(
`https://${this.#name}.com/${encode(key)}`,
new Response(
typeof value === 'string' || value instanceof Uint8Array
? value
: JSON.stringify(value),
{
headers: {
'cache-control': `max-age=${options?.maxAge ?? 300}`,
},
},
),
),
)
}
get<T extends Record<string, unknown> = Record<string, unknown>>(
key: string,
type: 'json',
): Promise<T | undefined>
get<T extends string = string>(
key: string,
type: 'string',
): Promise<T | undefined>
get<T extends Uint8Array = Uint8Array>(
key: string,
type: 'buffer',
): Promise<T | undefined>
async get<T extends Record<string, unknown> | string | Uint8Array>(
key: string,
type: 'string' | 'json' | 'buffer' = 'string',
): Promise<T | undefined> {
if (this.#cache === null) {
this.#cache = await caches.open(this.#name)
}
try {
const result = await this.#cache.match(
`https://${this.#name}.com/${encode(key)}`,
)
if (!result) {
return undefined
}
const data = type === 'string'
? await result.text()
: type === 'json'
? await result.json()
: new Uint8Array(await result.arrayBuffer())
return data
} catch (_err) {
return undefined
}
}
async has(key: string) {
if (this.#cache === null) {
this.#cache = await caches.open(this.#name)
}
const result = await this.#cache.match(
`https://${this.#name}.com/${encode(key)}`,
)
return result !== undefined
}
async delete(key: string) {
if (this.#cache === null) {
this.#cache = await caches.open(this.#name)
}
this.#context.waitUntil(
this.#cache.delete(
`https://${this.#name}.com/${encode(key)}`,
),
)
}
}