Files
SnowLuma/.pnpm-store/v11/files/00/fa7e5016004dd1abbf67302e48dc448321a977d6bb2114e31c8c2f98a0844947df83bd888315cda58a8768acce4216e386e44e7515122b888e3548460257ef
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

56 lines
1.3 KiB
Plaintext

Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/middleware/context-storage/index.ts
/**
* @module
* Context Storage Middleware for Hono.
*/
const asyncLocalStorage = new (require("node:async_hooks")).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
exports.contextStorage = contextStorage;
exports.getContext = getContext;
exports.tryGetContext = tryGetContext;