-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.ts
184 lines (169 loc) Β· 4.86 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
// Copyright 2022-2024 the oak authors. All rights reserved.
/**
* Contains the class {@linkcode Context} which provides context for the request
* and response to the request handler.
*
* @module
*/
import { createHttpError, SecureCookieMap, Status, UserAgent } from "./deps.ts";
import type { Deserializer, KeyRing } from "./types.ts";
import type {
Addr,
RequestEvent,
UpgradeWebSocketOptions,
} from "./types_internal.ts";
interface ContextOptions<BodyType, Params extends Record<string, string>> {
deserializer?: Deserializer<BodyType, Params>;
headers: Headers;
keys?: KeyRing;
params?: Params;
secure?: boolean;
requestEvent: RequestEvent;
}
/** An object that provides context for the associated request and response.
* This is passed as the first argument to every route handler. */
export class Context<
BodyType = unknown,
Params extends Record<string, string> = Record<string, string>,
> {
#body?: BodyType;
#bodySet = false;
#cookies: SecureCookieMap;
#deserializer?: Deserializer<BodyType, Params>;
#params: Params;
#requestEvent: RequestEvent;
#responded = false;
#searchParams?: Record<string, string>;
#url?: URL;
#userAgent: UserAgent;
/** The instance of {@linkcode Cookies} that allows reading and setting of
* cookies on the request and response. */
get cookies(): SecureCookieMap {
return this.#cookies;
}
/** Any {@linkcode Params} that have been parsed out of the URL requested
* based on the URL pattern string provided to the `Route`. */
get params(): Params {
return this.#params;
}
/** The original {@linkcode Request} associated with this request. */
get request(): Request {
return this.#requestEvent.request;
}
/**
* Indicates if the response has already been responded to, like when
* upgrading to a websocket.
*/
get responded(): boolean {
return this.#responded;
}
/** The address this request. */
get addr(): Addr {
return this.#requestEvent.addr;
}
/** Any search parameters associated with the request. */
get searchParams(): Record<string, string> {
if (!this.#searchParams) {
this.#searchParams = Object.fromEntries(
this.url().searchParams.entries(),
);
}
return this.#searchParams;
}
/**
* Information about the parsed user agent string associated with the
* {@linkcode Request} if available.
*
* See:
* [std/http/user_agent#UserAgent](https://deno.land/std/http/user_agent.ts?s=UserAgent)
* for more information.
*/
get userAgent(): UserAgent {
return this.#userAgent;
}
constructor(
{ requestEvent, keys, headers, secure, params, deserializer }:
ContextOptions<
BodyType,
Params
>,
) {
this.#requestEvent = requestEvent;
this.#params = params ?? {} as Params;
this.#deserializer = deserializer;
this.#cookies = new SecureCookieMap(requestEvent.request, {
keys,
response: headers,
secure,
});
this.#userAgent = new UserAgent(
requestEvent.request.headers.get("user-agent"),
);
}
/** A convenience method to deal with decoding a JSON string body. It can be
* used with an optional {@linkcode Deserializer} which can do advanced
* decoding of the body, or it will attempted to be decoded from the JSON
* string. */
async body(): Promise<BodyType | undefined> {
if (this.#bodySet) {
return this.#body;
}
this.#bodySet = true;
if (!this.#requestEvent.request.bodyUsed) {
if (this.#deserializer) {
const bodyString = await this.#requestEvent.request.text();
this.#body = await this.#deserializer.parse(
bodyString,
this.#params,
this.#requestEvent.request,
);
} else {
try {
this.#body = await this.#requestEvent.request.json();
} catch {
this.#body = undefined;
}
}
}
return this.#body;
}
/** Attempt to upgrade the request to a web socket, returning the socket and
* the response to be returned.
*
* ## Example
*
* ```ts
* import { Router } from "https://deno.land/x/acorn/mod.ts";
*
* const router = new Router();
*
* router.get("/ws", (ctx) => {
* const { socket, response } = ctx.upgrade();
* // Perform actions with the socket.
* return response;
* });
*
* router.listen({ port: 8000 });
* ```
*
* @param options
* @returns
*/
upgrade(options?: UpgradeWebSocketOptions): WebSocket {
if (!this.#requestEvent.upgrade) {
throw createHttpError(
Status.ServiceUnavailable,
"Web sockets not supported.",
);
}
this.#responded = true;
return this.#requestEvent.upgrade(options);
}
/** Returns the request URL as a parsed {@linkcode URL} object. */
url(): URL {
if (!this.#url) {
this.#url = new URL(this.#requestEvent.request.url);
}
return this.#url;
}
}