context.ts 588 B

12345678910111213141516171819202122232425
  1. import { AsyncLocalStorage } from "async_hooks"
  2. export namespace Context {
  3. export class NotFound extends Error {
  4. constructor(public override readonly name: string) {
  5. super(`No context found for ${name}`)
  6. }
  7. }
  8. export function create<T>(name: string) {
  9. const storage = new AsyncLocalStorage<T>()
  10. return {
  11. use() {
  12. const result = storage.getStore()
  13. if (!result) {
  14. throw new NotFound(name)
  15. }
  16. return result
  17. },
  18. provide<R>(value: T, fn: () => R) {
  19. return storage.run(value, fn)
  20. },
  21. }
  22. }
  23. }