-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontext.ts
41 lines (34 loc) · 826 Bytes
/
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
import type { ErrorInit } from "./types.ts";
import { ServerError } from "./types.ts";
export interface ContextInit {
request: Request;
params?: Record<string, string | undefined>;
}
const badRequest = {
status: 400,
message: "Invalid request: malformed request body.",
};
export class Context {
request: Request;
params: Record<string, string | undefined>;
status = 200;
constructor({ request, params }: ContextInit) {
this.request = request;
this.params = params ?? {};
}
get body() {
return this.request.json()
.catch(() => this.throw(badRequest));
}
throw(
error: ErrorInit,
// deno-fmt-ignore
) { throw new ServerError(error); }
assert(
expr: unknown,
error: ErrorInit,
): asserts expr {
if (expr) return;
throw new ServerError(error);
}
}