Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

async-local-storage.ts

34 lines1.0 KB

1import { AsyncLocalStorage } from 'node:async_hooks'
2import type { Awaitable, RegisteredRouter } from '@tanstack/router-core'
3​
4export interface StartStorageContext {
5 getRouter: () => Awaitable<RegisteredRouter>
6 request: Request
7 // TODO type this properly
8 startOptions: /* AnyStartInstanceOptions*/ any
9​
10 contextAfterGlobalMiddlewares: any
12​
13const startStorage = new AsyncLocalStorage<StartStorageContext>()
14​
15export async function runWithStartContext<T>(
16 context: StartStorageContext,
17 fn: () => T | Promise<T>,
18): Promise<T> {
19 return startStorage.run(context, fn)
21​
22export function getStartContext<TThrow extends boolean = true>(opts?: {
23 throwIfNotFound?: TThrow
24}): TThrow extends false
25 ? StartStorageContext | undefined
26 : StartStorageContext {
27 const context = startStorage.getStore()
28 if (!context && opts?.throwIfNotFound !== false) {
29 throw new Error(
30 `No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,
31 )
32 }
33 return context as any