33 lines
849 B
TypeScript
33 lines
849 B
TypeScript
|
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)
|
||
|
}
|
||
|
}
|