Files
SnowLuma/.pnpm-store/v11/files/89/3fc9a6ac4eb47fb722e9681dd3713efd5a2c17c5c132d951f25b80f242491cfe4fa9710e924edbe9613054f08c44f882ba1aa3e51623e76817de741b3293e5
T
TanTan 2a69b23b47
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

54 lines
1.1 KiB
Plaintext

import { AsyncLocalStorage } from "node:async_hooks";
//#region src/middleware/context-storage/index.ts
/**
* @module
* Context Storage Middleware for Hono.
*/
const asyncLocalStorage = new AsyncLocalStorage();
/**
* Context Storage Middleware for Hono.
*
* @see {@link https://hono.dev/docs/middleware/builtin/context-storage}
*
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* type Env = {
* Variables: {
* message: string
* }
* }
*
* const app = new Hono<Env>()
*
* app.use(contextStorage())
*
* app.use(async (c, next) => {
* c.set('message', 'Hono is hot!!')
* await next()
* })
*
* app.get('/', async (c) => c.text(getMessage()))
*
* const getMessage = () => {
* return getContext<Env>().var.message
* }
* ```
*/
const contextStorage = () => {
return async function contextStorage(c, next) {
await asyncLocalStorage.run(c, next);
};
};
const tryGetContext = () => {
return asyncLocalStorage.getStore();
};
const getContext = () => {
const context = tryGetContext();
if (!context) throw new Error("Context is not available");
return context;
};
//#endregion
export { contextStorage, getContext, tryGetContext };