You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
849 B
33 lines
849 B
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)
|
|
}
|
|
}
|