-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.ts
492 lines (414 loc) · 10.5 KB
/
request.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import {
ServerRequest,
getCookies,
Cookies,
Accepts,
qsStringify,
qsParse,
parse as contentTypeParse,
} from "./deps.ts";
import { typeofrequest } from "./utils/typeIs.ts";
import { HTTPMethods } from "./types.d.ts";
type Query = { [key: string]: string | string[] };
export class Request {
#serverRequest: ServerRequest;
#url?: URL;
#proxy: boolean;
#secure: boolean;
#accept: Accepts;
originalUrl: string;
req: ServerRequest;
constructor(request: ServerRequest, proxy = false, secure = false) {
this.#serverRequest = this.req = request;
this.#proxy = proxy;
this.#secure = secure;
this.#accept = new Accepts(this.#serverRequest.headers);
this.originalUrl = this.#serverRequest.url;
let proto: string;
let host: string;
if (this.#proxy) {
proto = this.#serverRequest
.headers.get("x-forwarded-proto")?.split(/\s*,\s*/, 1)[0] ??
"http";
host = this.#serverRequest.headers.get("x-forwarded-host") ??
this.#serverRequest.headers.get("host") ?? "";
} else {
proto = this.#secure ? "https" : "http";
host = this.#serverRequest.headers.get("host") ?? "";
}
}
get hasBody(): boolean {
return (
this.headers.get("transfer-encoding") !== null ||
!!parseInt(this.headers.get("content-length") ?? "")
);
}
/**
* Return request header.
*/
get header(): Headers {
return this.#serverRequest.headers;
}
set header(val) {
this.#serverRequest.headers = val;
}
/**
* Return request header, alias as request.header
*/
get headers(): Headers {
return this.#serverRequest.headers;
}
set headers(val: Headers) {
this.#serverRequest.headers = val;
}
get url() {
return this.#serverRequest.url;
}
set url(val: string) {
this.#serverRequest.url = val;
this.#url = new URL(`${this.protocol}://${this.host}${val}`);
}
/**
* Get WHATWG parsed URL object.
*/
get URL(): URL {
if (!this.#url) {
const serverRequest = this.#serverRequest;
let proto: string;
let host: string;
if (this.#proxy) {
proto = serverRequest
.headers.get("x-forwarded-proto")?.split(/\s*,\s*/, 1)[0] ??
"http";
host = serverRequest.headers.get("x-forwarded-host") ??
serverRequest.headers.get("host") ?? "";
} else {
proto = this.#secure ? "https" : "http";
host = serverRequest.headers.get("host") ?? "";
}
this.#url = new URL(`${proto}://${host}${serverRequest.url}`);
}
return this.#url;
}
/**
* Get origin of URL.
*/
get origin(): string {
return `${this.protocol}://${this.host}`;
}
/**
* Get full request URL.
*/
get href(): string {
if (/^https?:\/\//i.test(this.originalUrl)) return this.originalUrl;
return this.origin + this.originalUrl;
}
/**
* Get/Set request method.
*/
get method(): HTTPMethods {
return this.#serverRequest.method as HTTPMethods;
}
set method(val: HTTPMethods) {
this.#serverRequest.method = val;
}
/**
* Get request pathname.
* Set pathname, retaining the query-string when present.
*/
get path(): string {
return this.URL.pathname;
}
set path(path: string) {
if (this.URL.pathname === path) {
return;
}
this.URL.pathname = path;
this.#serverRequest.url = `${path}${this.URL.search}`;
}
/**
* Get parsed query-string.
* Set query-string as an object.
*/
get query(): Query {
const query: Query = {};
for (let [k, v] of new URLSearchParams(this.URL.search) as any) {
if (Array.isArray(query[k])) {
query[k] = [...query[k], v];
} else if (typeof query[k] === "string") {
query[k] = [query[k], v];
} else {
query[k] = v;
}
}
return query;
}
set query(obj: Query) {
this.querystring = qsStringify(obj);
}
get querystring(): string {
if (!(this as any).req) return "";
if (this.URL.search.length >= 1) {
return this.URL.search.slice(1);
} else {
return "";
}
}
set querystring(str: string) {
if (this.URL.search === `?${str}`) return;
this.URL.search = str;
this.url = `${this.URL.pathname}?${this.URL.search.slice(1)}`;
}
get search(): string {
return `?${this.querystring}`;
}
set search(str: string) {
this.querystring = str;
}
/**
* Parse the "Host" header field host
* and support X-Forwarded-Host when a
* proxy is enabled.
*/
get host(): string | null {
let host = this.#proxy && this.get("X-Forwarded-Host");
if (!host) host = this.get("Host");
if (!host) return "";
return host.split(/\s*,\s*/, 1)[0];
}
/**
* Parse the "Host" header field hostname
* and support X-Forwarded-Host when a
* proxy is enabled.
*/
get hostname() {
const host = this.host;
if (!host) return "";
if ("[" === host[0]) {
return this.URL.hostname || "";
}
return host.split(":", 1)[0];
}
/**
* Check if the request is fresh, aka
* Last-Modified and/or the ETag
* still match.
* @todo write fresh function
*/
get fresh() {
// TODO: write fresh method
return false;
}
/**
* Check if the request is stale, aka
* "Last-Modified" and / or the "ETag" for the
* resource has changed.
*/
get stale() {
return this.fresh;
}
/**
* Check if the request is idempotent.
*/
get idempotent(): boolean {
const methods = ["GET", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE"];
return !!~methods.indexOf(this.method);
}
/**
* Return the request conn.
*/
get socket(): Deno.Conn {
return this.#serverRequest.conn;
}
get cookies(): Cookies {
return getCookies(this.#serverRequest);
}
get protocol(): string {
return this.URL.protocol.split(":")[0];
}
/**
* Short-hand for:
*
* this.protocol == 'https'
*/
get secure(): boolean {
return this.#secure;
}
/**
* Return request's remote address
* When `app.proxy` is `true`, parse
* the "X-Forwarded-For" ip address list and return the first one
* @todo Implement this function.
*/
get ip(): string {
return this.#proxy
? this.ips[0]
: (this.#serverRequest.conn.remoteAddr as Deno.NetAddr).hostname;
}
/**
* When `app.proxy` is `true`, parse
* the "X-Forwarded-For" ip address list.
*
* For example if the value were "client, proxy1, proxy2"
* you would receive the array `["client", "proxy1", "proxy2"]`
* where "proxy2" is the furthest down-stream.
* @todo Implement this function.
*/
get ips(): string[] {
return this.#proxy
? (this.#serverRequest.headers.get("x-forwarded-for") ??
(this.#serverRequest.conn.remoteAddr as Deno.NetAddr).hostname).split(
/\s*,\s*/,
)
: [];
}
/**
* Return request header. If the header is not set, will return an empty
* string.
*
* The `Referrer` header field is special-cased, both `Referrer` and
* `Referer` are interchangeable.
*
* Examples:
*
* this.get('Content-Type');
* // => "text/plain"
*
* this.get('content-type');
* // => "text/plain"
*
* this.get('Something');
* // => ''
*/
public get(field: string): string {
switch (field = field.toLowerCase()) {
case "referer":
case "referrer":
return this.#serverRequest.headers.get("referrer") ||
this.#serverRequest.headers.get("referer") || "";
default:
return this.#serverRequest.headers.get(field) || "";
}
}
/**
* Check whether the response is one of the listed types.
*
* @param {String|Array} types...
* @return {String|false}
* @api public
*/
public is(types: string | string[]): string | boolean | null {
let arr = types;
if (!Array.isArray(types)) {
arr = new Array(arguments.length);
for (let i = 0; i < arr.length; i++) {
arr[i] = arguments[i];
}
}
return typeofrequest(this.#serverRequest.headers, arr as string[]);
}
/**
* Return the request mime type void of
* parameters such as "charset".
*/
get type(): string {
const type = this.get("Content-Type");
if (!type) return "";
return type.split(";")[0];
}
public xhr(): Boolean {
const val = this.get("X-Requested-With") || "";
return val.toLowerCase() === "xmlhttprequest";
}
/**
* Get the charset when present or empty.
*/
get charset(): string {
try {
const { parameters } = contentTypeParse(this.get("Content-Type"));
return (parameters && parameters.charset) || "";
} catch (e) {
return "";
}
}
/**
* Return parsed Content-Length when present.
*/
get length(): number | undefined {
const len = this.get("Content-Length");
if (len == "") return;
return ~~len;
}
accepts(...types: string[]): string | string[] | undefined | boolean {
types = Array.isArray(types[0]) ? types[0] : types;
const res = this.accept.types(types);
if (res.length === 0) {
return false;
}
if (res.length === 1 && !!types.length) {
return res[0];
}
return res;
}
acceptsCharsets(...types: string[]): string | string[] | undefined | boolean {
types = Array.isArray(types[0]) ? types[0] : types;
const res = this.accept.charsets(types);
if (res.length === 0) {
return false;
}
if (res.length === 1 && !!types.length) {
return res[0];
}
return res;
}
acceptsEncodings(
...types: string[]
): string | string[] | undefined | boolean {
types = Array.isArray(types[0]) ? types[0] : types;
const res = this.accept.encodings(types);
if (res.length === 0) {
return false;
}
if (res.length === 1 && !!types.length) {
return res[0];
}
return res;
}
acceptsLanguages(
...types: string[]
): string | string[] | undefined | boolean {
types = Array.isArray(types[0]) ? types[0] : types;
const res = this.accept.languages(types);
if (res.length === 0) {
return false;
}
if (res.length === 1 && !!types.length) {
return res[0];
}
return res;
}
get accept() {
return this.#accept ||
(this.#accept = new Accepts(this.#serverRequest.headers));
}
set accept(obj) {
this.#accept = obj;
}
/**
* Inspect implementation.
*/
inspect() {
if (!this.#serverRequest) return;
return this.toJSON();
}
/**
* Return JSON representation.
*/
public toJSON() {
return {
method: this.method,
url: this.url,
header: this.header,
};
}
}