summaryrefslogtreecommitdiffhomepage
path: root/packages/console/core/src/context.ts
blob: c2ca6a313645ec8b65885313d95b752ae73b621c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { AsyncLocalStorage } from "node:async_hooks"

export namespace Context {
  export class NotFound extends Error {}

  export function create<T>() {
    const storage = new AsyncLocalStorage<T>()
    return {
      use() {
        const result = storage.getStore()
        if (!result) {
          throw new NotFound()
        }
        return result
      },
      provide<R>(value: T, fn: () => R) {
        return storage.run<R>(value, fn)
      },
    }
  }
}