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 = new AsyncLocalStorage() get(): Request { const req = this.store.getStore() if ( !req ) { throw new InvalidOutOfRequestAccessError() } return req } has(): boolean { return Boolean(this.store.getStore()) } run(req: Request, closure: () => T): T { return this.store.run(req, closure) } }