-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.js
118 lines (97 loc) · 2.48 KB
/
request.js
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
const os = require('os')
const qs = require('qs')
const accepts = require('accepts')
const parseRange = require('range-parser')
const { trustProxy } = require('./constants')
class Request {
constructor (connection) {
this._accepts = accepts(connection)
this.connection = connection
this._cache = {}
}
static create (connection) {
return new Request(connection)
}
get body () {
return this.connection.bodyData()
}
get bodyStream () {
return this.connection.bodyDataStream()
}
get hostname () {
const headers = this.connection.headers
return headers.host || headers['x-forwarded-host'] || os.hostname()
}
get subdomains () {
return this.hostname.split(/\./g).slice(0, -2)
}
get query () {
if (!this._cache.query) {
this._cache.query = qs.parse(this.connection.rawQuery)
}
return this._cache.query
}
get ip () {
return this.connection.remoteAddress
}
get realIp () {
const app = this.connection.app
const trustMatcher = app.getParam(trustProxy)
const headers = this.connection.headers
const realIp = headers['x-real-ip']
if (realIp && trustMatcher.contains(this.ip)) {
return realIp
}
return this.ip
}
get ips () {
const app = this.connection.app
const matcher = app.getParam(trustProxy)
const xff = (this.connection.headers['x-forwarded-for'] || '').split(/, */g)
.filter(Boolean)
const trusted = [this.ip]
if (xff.length > 0 && matcher.contains(this.ip)) {
for (const ip of xff) {
if (matcher.contains(ip)) {
trusted.push(ip)
} else {
break
}
}
trusted.push(xff[trusted.length - 1])
}
return trusted
}
get method () {
return this.connection.method
}
has (name) {
return name.toLowerCase() in this.connection.headers
}
get (name) {
return this.connection.headers[name.toLowerCase()]
}
get xhr () {
const value = this.connection.headers['x-requested-with'] || ''
return value.toLowerCase() === 'xmlhttprequest'
}
is (type) {
return this._accepts.type(type)
}
accepts (types) {
return this._accepts.types(types)
}
acceptsCharsets () {
return this._accepts.charsets()
}
acceptsEncodings () {
return this._accepts.encodings()
}
acceptsLanguages () {
return this._accepts.languages()
}
range (size) {
return parseRange(size, this.connection.headers.range || '', { combine: true })
}
}
module.exports = Request