-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequest.ts
More file actions
215 lines (194 loc) · 6.9 KB
/
Request.ts
File metadata and controls
215 lines (194 loc) · 6.9 KB
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
import {Multipart} from "multipart-ts";
import http, {OutgoingHttpHeader} from "node:http";
import stream from "node:stream";
/**
* An incoming HTTP request from a connected client.
*/
export class Request {
/**
* The request method.
*/
public readonly method: Request.Method;
/**
* The request URL.
*/
public readonly url: Readonly<URL>;
/**
* The request headers.
*/
public readonly headers: Readonly<Headers>;
/**
* Request body readable stream.
*/
public readonly bodyStream: stream.Readable;
/**
* Construct a new Request.
* @param method See {@link Request#method}.
* @param url See {@link Request#url}.
* @param headers See {@link Request#headers}.
* @param bodyStream See {@link Request#bodyStream}.
*/
protected constructor(
method: Request["method"],
url: Request["url"],
headers: Request["headers"],
bodyStream: Request["bodyStream"],
) {
this.method = method;
this.url = url;
this.headers = headers;
this.bodyStream = bodyStream;
}
/**
* Create a new Request from a Node.js incoming HTTP request.
* @throws {@link Request.BadUrlError} If the request URL is invalid.
*/
public static incomingMessage(incomingMessage: http.IncomingMessage) {
const auth =
incomingMessage.headers.authorization
?.toLowerCase()
.startsWith("basic ")
? Buffer.from(
incomingMessage.headers.authorization
.substring("basic ".length), "base64"
).toString()
: null;
const url = `http://${auth ? `${auth}@` : ""}${process.env.HOST ?? "localhost"}${incomingMessage.url ?? "/"}`;
if (!URL.canParse(url))
throw new Request.BadUrlError(incomingMessage.url);
const headers = Request.headersFromNodeDict(incomingMessage.headers);
return new Request(incomingMessage.method as Request.Method, new URL(url), headers, incomingMessage);
}
/**
* @internal
*/
public static headersFromNodeDict(headers: Record<string, OutgoingHttpHeader | undefined>): Headers {
return new Headers(Object.entries(headers)
.filter((e) => e[1] !== undefined)
.flatMap<[string, string]>(([key, value]) =>
value instanceof Array
? value.map<[string, string]>(v => [key, v])
: [[key, String(value)]]
)
);
}
/**
* Returns a boolean value that declares whether the body has been read yet.
*/
public bodyUsed(): boolean {
return this.bodyStream.readable && !this.bodyStream.readableDidRead;
}
/**
* Returns a promise that resolves with an ArrayBuffer representation of the request body.
* @throws {@link Request.BodyAlreadyConsumedError} If the request body has already been consumed.
*/
public async arrayBuffer(): Promise<ArrayBuffer> {
return (await this.blob()).arrayBuffer();
}
/**
* Returns a promise that resolves with a Blob representation of the request body.
* @throws {@link Request.BodyAlreadyConsumedError} If the request body has already been consumed.
*/
public async blob(): Promise<Blob> {
if (this.bodyUsed()) throw new Request.BodyAlreadyConsumedError();
const chunks: Uint8Array[] = [];
for await (const chunk of this.bodyStream)
chunks.push(chunk);
return new Blob(chunks, {type: this.headers.get("Content-Type") ?? undefined});
}
/**
* Returns a promise that resolves with a Uint8Array representation of the request body.
* @throws {@link Request.BodyAlreadyConsumedError} If the request body has already been consumed.
*/
public async bytes(): Promise<Uint8Array> {
return (await this.blob()).bytes();
}
/**
* Returns a promise that resolves with a FormData representation of the request body.
* @throws {@link Request.BodyAlreadyConsumedError} If the request body has already been consumed.
* @throws {@link !TypeError} If the request body cannot be parsed as multipart.
*/
public async formData(): Promise<FormData> {
return (await this.multipart()).formData();
}
/**
* Returns a promise that resolves with the result of parsing the request body as JSON.
* @throws {@link Request.BodyAlreadyConsumedError} If the request body has already been consumed.
* @throws {@link !SyntaxError} If the request body cannot be parsed as JSON.
*/
public async json(): Promise<unknown> {
return JSON.parse(await this.text());
}
/**
* Returns a promise that resolves with a FormData representation of the request body.
* @throws {@link Request.BodyAlreadyConsumedError} If the request body has already been consumed.
* @throws {@link !TypeError} If the request body cannot be parsed as multipart.
*/
public async multipart(): Promise<Multipart> {
const type = this.headers.get("Content-Type");
if (!type)
throw new TypeError("No Content-Type header; cannot determine multipart boundary");
return Multipart.blob(await this.blob());
}
/**
* Returns a promise that resolves with a text representation of the request body.
* @throws {@link Request.BodyAlreadyConsumedError} If the request body has already been consumed.
*/
public async text(): Promise<string> {
return (await this.blob()).text();
}
}
export namespace Request {
export class BadUrlError extends Error {
public constructor(public readonly path: string | undefined) {
super(`${path} is not a valid URL.`);
}
}
/**
* The request body has already been consumed.
*/
export class BodyAlreadyConsumedError extends Error {
public constructor() {
super("Body has already been consumed.");
}
}
/**
* HTTP request methods.
*/
export const enum Method {
ACL = "ACL",
BIND = "BIND",
CHECKOUT = "CHECKOUT",
CONNECT = "CONNECT",
COPY = "COPY",
DELETE = "DELETE",
GET = "GET",
HEAD = "HEAD",
LINK = "LINK",
LOCK = "LOCK",
"M-SEARCH" = "M-SEARCH",
MERGE = "MERGE",
MKACTIVITY = "MKACTIVITY",
MKCALENDAR = "MKCALENDAR",
MKCOL = "MKCOL",
MOVE = "MOVE",
NOTIFY = "NOTIFY",
OPTIONS = "OPTIONS",
PATCH = "PATCH",
POST = "POST",
PROPFIND = "PROPFIND",
PROPPATCH = "PROPPATCH",
PURGE = "PURGE",
PUT = "PUT",
REBIND = "REBIND",
REPORT = "REPORT",
SEARCH = "SEARCH",
SOURCE = "SOURCE",
SUBSCRIBE = "SUBSCRIBE",
TRACE = "TRACE",
UNBIND = "UNBIND",
UNLINK = "UNLINK",
UNLOCK = "UNLOCK",
UNSUBSCRIBE = "UNSUBSCRIBE",
}
}