-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
request.ts
616 lines (557 loc) · 16.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/**
* @adonisjs/http-server
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare module '@ioc:Adonis/Core/Request' {
import { UrlWithStringQuery } from 'url'
import { MacroableConstructorContract } from 'macroable'
import { EncryptionContract } from '@ioc:Adonis/Core/Encryption'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'
/**
* Shape of the request class instance
*/
export interface RequestContract {
/**
* Parses copy of the URL with query string as a string and not
* object. This is done to build URL's with query string without
* stringifying the object
*/
parsedUrl: UrlWithStringQuery
request: IncomingMessage
response: ServerResponse
/**
* The ctx will be set by the context itself. It creates a circular
* reference
*/
ctx?: HttpContextContract
/**
* Returns the request id from the `x-request-id` header. The
* header is untoched, if it already exists.
*/
id(): string | undefined
/**
* Set initial request body. A copy of the input will be maintained as the original
* request body. Since the request body and query string is subject to mutations, we
* keep one original reference to flash old data (whenever required).
*
* This method is supposed to be invoked by the body parser and must be called only
* once. For further mutations make use of `updateBody` method.
*/
setInitialBody(body: Record<string, any>): void
/**
* Update the request body with new data object. The `all` property
* will be re-computed by merging the query string and request
* body.
*/
updateBody(body: Record<string, any>): void
/**
* Update the request raw body. Bodyparser sets this when unable to parse
* the request body or when request is multipart/form-data.
*/
updateRawBody(body: string): void
/**
* Update route params
*/
updateParams(body: Record<string, any>): void
/**
* Update the query string with the new data object. The `all` property
* will be re-computed by merging the query and the request body.
*/
updateQs(data: Record<string, any>): void
/**
* Returns route params
*/
params(): Record<string, any>
/**
* Returns reference to the query string object
* @deprecated: Use ".qs()" instead
*/
get(): Record<string, any>
/**
* Returns the query string object by reference
*/
qs(): Record<string, any>
/**
* Returns the request body object by reference
* @deprecated: Use ".body()" instead
*/
post(): Record<string, any>
/**
* Returns the request body object by reference
*/
body(): Record<string, any>
/**
* Returns reference to the merged copy of original request
* query string and body
*/
original(): Record<string, any>
/**
* Returns reference to the merged copy of request body
* and query string
*/
all(): Record<string, any>
/**
* Returns the request raw body (if exists), or returns `null`.
*
* Ideally you must be dealing with the parsed body accessed using [[input]], [[all]] or
* [[post]] methods. The `raw` body is always a string.
*/
raw(): string | null
/**
* Returns value for a given key from the request body or query string.
* The `defaultValue` is used when original value is `undefined`.
*
* @example
* ```js
* request.input('username')
*
* // with default value
* request.input('username', 'virk')
* ```
*/
input(key: string, defaultValue?: any): any
/**
* Returns value for a given key from route params
*
* @example
* ```js
* request.param('id')
*
* // with default value
* request.param('id', 1)
* ```
*/
param(key: string, defaultValue?: any): any
/**
* Get everything from the request body except the given keys.
*
* @example
* ```js
* request.except(['_csrf'])
* ```
*/
except(keys: string[]): Record<string, any>
/**
* Get value for specified keys.
*
* @example
* ```js
* request.only(['username', 'age'])
* ```
*/
only<T extends string>(keys: T[]): { [K in T]: any }
/**
* Returns the request HTTP method by taking method spoofing into account.
*
* Method spoofing works when all of the following are true.
*
* 1. `app.http.allowMethodSpoofing` config value is true.
* 2. request query string has `_method`.
* 3. The [[intended]] request method is `POST`.
*
* @example
* ```js
* request.method()
* ```
*/
method(): string
/**
* Returns the HTTP request method. This is the original
* request method. For spoofed request method, make
* use of [[method]].
*
* @example
* ```js
* request.intended()
* ```
*/
intended(): string
/**
* Returns a copy of headers as an object
*/
headers(): IncomingHttpHeaders
/**
* Returns value for a given header key. The default value is
* used when original value is `undefined`.
*/
header(key: string, defaultValue?: any): string | undefined
/**
* Returns the ip address of the user. This method is optimize to fetch
* ip address even when running your AdonisJs app behind a proxy.
*
* You can also define your own custom function to compute the ip address by
* defining `app.http.getIp` as a function inside the config file.
*
* ```js
* {
* http: {
* getIp (request) {
* // I am using nginx as a proxy server and want to trust 'x-real-ip'
* return request.header('x-real-ip')
* }
* }
* }
* ```
*
* You can control the behavior of trusting the proxy values by defining it
* inside the `config/app.js` file.
*
* ```js
* {
* http: {
* trustProxy: '127.0.0.1'
* }
* }
* ```
*
* The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr)
*/
ip(): string
/**
* Returns an array of ip addresses from most to least trusted one.
* This method is optimize to fetch ip address even when running
* your AdonisJs app behind a proxy.
*
* You can control the behavior of trusting the proxy values by defining it
* inside the `config/app.js` file.
*
* ```js
* {
* http: {
* trustProxy: '127.0.0.1'
* }
* }
* ```
*
* The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr)
*/
ips(): string[]
/**
* Returns the request protocol by checking for the URL protocol or
* `X-Forwarded-Proto` header.
*
* If the `trust` is evaluated to `false`, then URL protocol is returned,
* otherwise `X-Forwarded-Proto` header is used (if exists).
*
* You can control the behavior of trusting the proxy values by defining it
* inside the `config/app.js` file.
*
* ```js
* {
* http: {
* trustProxy: '127.0.0.1'
* }
* }
* ```
*
* The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr)
*/
protocol(): string
/**
* Returns a boolean telling if request is served over `https`
* or not. Check [[protocol]] method to know how protocol is
* fetched.
*/
secure(): boolean
/**
* Returns an array of subdomains for the given host. An empty array is
* returned if [[hostname]] is `null` or is an IP address.
*
* Also `www` is not considered as a subdomain
*/
subdomains(): string[]
/**
* Returns the request host. If proxy headers are trusted, then
* `X-Forwarded-Host` is given priority over the `Host` header.
*
* You can control the behavior of trusting the proxy values by defining it
* inside the `config/app.js` file.
*
* ```js
* {
* http: {
* trustProxy: '127.0.0.1'
* }
* }
* ```
*
* The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr)
*/
host(): string | null
/**
* Returns the request hostname. The hostname value does not include the
* port.
*/
hostname(): string | null
/**
* Returns a boolean telling, if request `X-Requested-With === 'xmlhttprequest'`
* or not.
*/
ajax(): boolean
/**
* Returns a boolean telling, if request has `X-Pjax` header
* set or not
*/
pjax(): boolean
/**
* Returns the request relative URL.
*
* @example
* ```js
* request.url()
*
* // include query string
* request.url(true)
* ```
*/
url(includeQueryString?: boolean): string
/**
* Returns the complete HTTP url by combining
* [[protocol]]://[[hostname]]/[[url]]
*
* @example
* ```js
* request.completeUrl()
*
* // include query string
* request.completeUrl(true)
* ```
*/
completeUrl(includeQueryString?: boolean): string
/**
* Find if the current HTTP request is for the given route or the routes
*/
matchesRoute(routeIdentifier: string | string[]): boolean
/**
* Returns the best matching content type of the request by
* matching against the given types.
*
* The content type is picked from the `content-type` header and request
* must have body.
*
* The method response highly depends upon the types array values. Described below:
*
* | Type(s) | Return value |
* |----------|---------------|
* | ['json'] | json |
* | ['application/*'] | application/json |
* | ['vnd+json'] | application/json |
*
* @example
* ```js
* const bodyType = request.is(['json', 'xml'])
*
* if (bodyType === 'json') {
* // process JSON
* }
*
* if (bodyType === 'xml') {
* // process XML
* }
* ```
*/
is(types: string[]): string | null
/**
* Returns the best type using `Accept` header and
* by matching it against the given types.
*
* If nothing is matched, then `null` will be returned
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*
* @example
* ```js
* switch (request.accepts(['json', 'html'])) {
* case 'json':
* return response.json(user)
* case 'html':
* return view.render('user', { user })
* default:
* // decide yourself
* }
* ```
*/
accepts<T extends string>(types: T[]): T | null
/**
* Return the types that the request accepts, in the order of the
* client's preference (most preferred first).
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*/
types(): string[]
/**
* Returns the best language using `Accept-language` header
* and by matching it against the given languages.
*
* If nothing is matched, then `null` will be returned
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*
* @example
* ```js
* switch (request.language(['fr', 'de'])) {
* case 'fr':
* return view.render('about', { lang: 'fr' })
* case 'de':
* return view.render('about', { lang: 'de' })
* default:
* return view.render('about', { lang: 'en' })
* }
* ```
*/
language<T extends string>(languages: T[]): T | null
/**
* Return the languages that the request accepts, in the order of the
* client's preference (most preferred first).
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*/
languages(): string[]
/**
* Returns the best encoding using `Accept-encoding` header
* and by matching it against the given encodings.
*
* If nothing is matched, then `null` will be returned
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*/
encoding<T extends string>(encodings: T[]): T | null
/**
* Return the charsets that the request accepts, in the order of the
* client's preference (most preferred first).
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*/
encodings(): string[]
/**
* Returns the best charset using `Accept-charset` header
* and by matching it against the given charsets.
*
* If nothing is matched, then `null` will be returned
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*
* @example
* ```js
* switch (request.charset(['utf-8', 'ISO-8859-1'])) {
* case 'utf-8':
* // make utf-8 friendly response
* case 'ISO-8859-1':
* // make ISO-8859-1 friendly response
* }
* ```
*/
charset<T extends string>(charsets: T[]): T | null
/**
* Return the charsets that the request accepts, in the order of the
* client's preference (most preferred first).
*
* Make sure to check [accepts](https://www.npmjs.com/package/accepts) package
* docs too.
*/
charsets(): string[]
/**
* Returns a boolean telling if request has body
*/
hasBody(): boolean
/**
* Returns a boolean telling if the new response etag evaluates same
* as the request header `if-none-match`. In case of `true`, the
* server must return `304` response, telling the browser to
* use the client cache.
*
* You won't have to deal with this method directly, since AdonisJs will
* handle this for you when `http.etag = true` inside `config/app.js` file.
*
* However, this is how you can use it manually.
*
* @example
* ```js
* const responseBody = view.render('some-view')
*
* // sets the HTTP etag header for response
* response.setEtag(responseBody)
*
* if (request.fresh()) {
* response.sendStatus(304)
* } else {
* response.send(responseBody)
* }
* ```
*/
fresh(): boolean
/**
* Opposite of [[fresh]]
*/
stale(): boolean
/**
* Returns all parsed and signed cookies. Signed cookies ensures
* that their value isn't tampered.
*/
cookiesList(): Record<string, any>
/**
* Returns value for a given key from signed cookies. Optional
* defaultValue is returned when actual value is undefined.
*/
cookie(key: string, defaultValue?: any): any
/**
* Returns value for a given key from signed cookies. Optional
* defaultValue is returned when actual value is undefined.
*/
encryptedCookie(key: string, defaultValue?: any): any
/**
* Returns value for a given key from unsigned cookies. Optional
* defaultValue is returned when actual value is undefined.
*/
plainCookie(key: string, defaultValue?: any): any
/**
* Returns a boolean telling if a signed url as a valid signature
* or not.
*/
hasValidSignature(purpose?: string): boolean
/**
* toJSON copy of the request
*/
toJSON(): any
}
/**
* Shape of the request config
*/
export type RequestConfig = {
forceContentNegotiationTo?: string
subdomainOffset: number
generateRequestId: boolean
allowMethodSpoofing: boolean
getIp?: (request: RequestContract) => string
trustProxy: (address: string, distance: number) => boolean
enableAsyncHttpContext?: boolean
}
/**
* Shape of request constructor, we export the constructor for others to
* add macros to the request class. Since, the instance is passed
* to the http request cycle
*/
export interface RequestConstructorContract
extends MacroableConstructorContract<RequestContract> {
new (
request: IncomingMessage,
response: ServerResponse,
encryption: EncryptionContract,
config: RequestConfig
): RequestContract
}
const Request: RequestConstructorContract
export default Request
}