Introduce async local storage for request access, more view globals, and improved welcome view
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
32
src/http/RequestLocalStorage.ts
Normal file
32
src/http/RequestLocalStorage.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks'
|
||||
import {Request} from './lifecycle/Request'
|
||||
import {Singleton} from '../di'
|
||||
import {ErrorWithContext} from '../util'
|
||||
|
||||
export class InvalidOutOfRequestAccessError extends ErrorWithContext {
|
||||
constructor() {
|
||||
super(`Attempted to access request via local storage outside of async lifecycle!`)
|
||||
}
|
||||
}
|
||||
|
||||
@Singleton()
|
||||
export class RequestLocalStorage {
|
||||
protected readonly store: AsyncLocalStorage<Request> = new AsyncLocalStorage<Request>()
|
||||
|
||||
get(): Request {
|
||||
const req = this.store.getStore()
|
||||
if ( !req ) {
|
||||
throw new InvalidOutOfRequestAccessError()
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
has(): boolean {
|
||||
return Boolean(this.store.getStore())
|
||||
}
|
||||
|
||||
run<T>(req: Request, closure: () => T): T {
|
||||
return this.store.run(req, closure)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user