-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.ts
49 lines (40 loc) · 1.27 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
/**
* @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 { AsyncLocalStorage } from 'async_hooks'
import { Exception } from '@poppinss/utils'
import { AsyncHttpContextContract } from '@ioc:Adonis/Core/AsyncHttpContext'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
const adonisLocalStorage = new AsyncLocalStorage<InternalAsyncHttpContext>()
export class InternalAsyncHttpContext {
constructor(private ctx: HttpContextContract) {}
public getContext() {
return this.ctx
}
public run(callback: () => any) {
return adonisLocalStorage.run(this, callback)
}
}
class AsyncHttpContext implements AsyncHttpContextContract {
public getContext() {
const store = adonisLocalStorage.getStore()
if (store) {
return store.getContext()
}
return null
}
public getContextOrFail() {
const store = adonisLocalStorage.getStore()
if (store) {
return store.getContext()
}
throw new Exception('AsyncHttpContext accessed outside of a request context')
}
}
export const asyncHttpContext = new AsyncHttpContext()