forked from adonisjs/http-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
200 lines (175 loc) · 5.15 KB
/
index.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
/**
* @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.
*/
/// <reference path="../../adonis-typings/index.ts" />
import { Socket } from 'net'
import { inspect } from 'util'
import { Macroable } from 'macroable'
import { RouteNode } from '@ioc:Adonis/Core/Route'
import { IncomingMessage, ServerResponse } from 'http'
import { LoggerContract } from '@ioc:Adonis/Core/Logger'
import { RequestContract } from '@ioc:Adonis/Core/Request'
import { ResponseContract } from '@ioc:Adonis/Core/Response'
import { ProfilerRowContract } from '@ioc:Adonis/Core/Profiler'
import { ApplicationContract } from '@ioc:Adonis/Core/Application'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { Request } from '../Request'
import { Response } from '../Response'
import { processPattern } from '../helpers'
import { adonisLocalStorage, asyncHttpContextEnabled } from '../AsyncHttpContext'
import { Exception } from '@poppinss/utils'
/**
* Http context is passed to all route handlers, middleware,
* error handler and server hooks.
*/
export class HttpContext extends Macroable implements HttpContextContract {
/**
* Set inside the provider
*/
public static app: ApplicationContract
public static get asyncHttpContextEnabled() {
return asyncHttpContextEnabled
}
public static get(): HttpContextContract | null {
const store = adonisLocalStorage.getStore()
return store !== undefined ? store.getContext() : null
}
public static getOrFail() {
const store = adonisLocalStorage.getStore()
if (store !== undefined) {
return store.getContext()
}
if (asyncHttpContextEnabled) {
throw new Exception('async HTTP context accessed outside of a request context')
} else {
throw new Exception('async HTTP context is disabled')
}
}
/**
* A unique key for the current route
*/
public routeKey: string
/**
* Route params
*/
public params: Record<string, any> = {}
/**
* Route subdomains
*/
public subdomains: Record<string, any> = {}
/**
* Reference to the current route. Not available inside
* server hooks
*/
public route?: RouteNode
/**
* Required by macroable
*/
protected static macros = {}
protected static getters = {}
constructor(
public request: RequestContract,
public response: ResponseContract,
public logger: LoggerContract,
public profiler: ProfilerRowContract
) {
super()
/*
* Creating the circular reference. We do this, since request and response
* are meant to be extended and at times people would want to access
* other ctx properties like `logger`, `profiler` inside those
* extended methods.
*/
this.request.ctx = this
this.response.ctx = this
}
/**
* A helper to see top level properties on the context object
*/
public inspect() {
return inspect(this, false, 1, true)
}
/**
* Creates a new fake context instance for a given route. The method is
* meant to be used inside an AdonisJS application since it relies
* directly on the IoC container.
*/
public static create(
routePattern: string,
routeParams: Record<string, any>,
req?: IncomingMessage,
res?: ServerResponse
) {
const Router = HttpContext.app.container.resolveBinding('Adonis/Core/Route')
const Encryption = HttpContext.app.container.resolveBinding('Adonis/Core/Encryption')
const serverConfig = HttpContext.app.container
.resolveBinding('Adonis/Core/Config')
.get('app.http', {})
req = req || new IncomingMessage(new Socket())
res = res || new ServerResponse(req)
/*
* Creating the url from the router pattern and params. Only
* when actual URL isn't defined.
*/
req.url = req.url || processPattern(routePattern, routeParams)
/*
* Creating new request instance
*/
const request = new Request(req, res, Encryption, {
allowMethodSpoofing: serverConfig.allowMethodSpoofing,
subdomainOffset: serverConfig.subdomainOffset,
trustProxy: serverConfig.trustProxy,
generateRequestId: serverConfig.generateRequestId,
})
/*
* Creating new response instance
*/
const response = new Response(
req,
res,
Encryption,
{
etag: serverConfig.etag,
cookie: serverConfig.cookie,
jsonpCallbackName: serverConfig.jsonpCallbackName,
},
Router
)
/*
* Creating new ctx instance
*/
const ctx = new HttpContext(
request,
response,
this.app.logger.child({}),
this.app.profiler.create('http:context')
)
/*
* Attaching route to the ctx
*/
ctx.route = {
pattern: routePattern,
middleware: [],
handler: async () => 'handled',
meta: {},
}
/*
* Defining route key
*/
ctx.routeKey = `${request.method()}-${ctx.route.pattern}`
/*
* Attaching params to the ctx
*/
ctx.params = routeParams
/**
* Set params on the request
*/
ctx.request.updateParams(routeParams)
return ctx
}
}