index.ts
This file
Path
src/middleware/context-storage/index.ts
59 lines · 1.3 KiB · TypeScript
Last changed by
docs(context-storage): fix JSDoc (#5086)Yusuke Wadabefore adoptiond6b1d32
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–31why, one step back1/**2 * @module3 * Context Storage Middleware for Hono.4 */56import { AsyncLocalStorage } from 'node:async_hooks'7import type { Context } from '../../context'8import type { Env, MiddlewareHandler } from '../../types'910const asyncLocalStorage = new AsyncLocalStorage<Context>()1112/**13 * Context Storage Middleware for Hono.14 *15 * @see {@link https://hono.dev/docs/middleware/builtin/context-storage}16 *17 * @returns {MiddlewareHandler} The middleware handler function.18 *19 * @example20 * ```ts21 * type Env = {22 * Variables: {23 * message: string24 * }25 * }26 *27 * const app = new Hono<Env>()28 *29 * app.use(contextStorage())30 *31 * app.use(async (c, next) => {docs(context-storage): fix JSDoc (#5086)Yusuke Wadabefore adoptiond6b1d32
line 32why, one step back32 * c.set('message', 'Hono is hot!!')Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 33–35why, one step back33 * await next()34 * })35 *docs(context-storage): fix JSDoc (#5086)Yusuke Wadabefore adoptiond6b1d32
line 36why, one step back36 * app.get('/', async (c) => c.text(getMessage()))Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 37–59why, one step back37 *38 * const getMessage = () => {39 * return getContext<Env>().var.message40 * }41 * ```42 */43export const contextStorage = (): MiddlewareHandler => {44 return async function contextStorage(c, next) {45 await asyncLocalStorage.run(c, next)46 }47}4849export const tryGetContext = <E extends Env = Env>(): Context<E> | undefined => {50 return asyncLocalStorage.getStore() as Context<E> | undefined51}5253export const getContext = <E extends Env = Env>(): Context<E> => {54 const context = tryGetContext<E>()55 if (!context) {56 throw new Error('Context is not available')57 }58 return context59}