diff --git a/src/middleware/hook/index.ts b/src/middleware/hook/index.ts index 65552bd2..719468c0 100644 --- a/src/middleware/hook/index.ts +++ b/src/middleware/hook/index.ts @@ -3,8 +3,13 @@ import type { Env, Handler, MiddlewareHandler, Next } from '../../types' const isWrapped = Symbol() -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export type Hook = (c: Context, handler: Handler, handlerContext: Record) => void +export type Hook = ( + c: Context, + handler: Handler, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + handlerContext: Record, + traceId: string +) => void export const hook = ( options: { before?: Hook @@ -14,6 +19,9 @@ export const hook = ( } = {} ): MiddlewareHandler => { function hook(c: Context, next: Next) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + c.set('middleware-hook-trace-id' as any, Math.random().toString(16).slice(2)) + // eslint-disable-next-line @typescript-eslint/no-explicit-any ;(c.req.matchResult[0] as unknown as [[any]][]).forEach((routeData) => { if (routeData[0][0][isWrapped]) { @@ -25,21 +33,22 @@ export const hook = ( routeData[0][0] = { [name]: function (c: Context, next: Next) { const handlerContext = Object.create(null) + const traceId = c.get('middleware-hook-trace-id') if (options.before) { - options.before?.(c, handler, handlerContext) + options.before?.(c, handler, handlerContext, traceId) } const internalNext = () => { - options.beforeNext?.(c, handler, handlerContext) + options.beforeNext?.(c, handler, handlerContext, traceId) const res = next() - res.finally(() => options.afterNext?.(c, handler, handlerContext)) + res.finally(() => options.afterNext?.(c, handler, handlerContext, traceId)) return res } const res = handler(c, internalNext) if (res instanceof Promise) { - res.finally(() => options.after?.(c, handler, handlerContext)) + res.finally(() => options.after?.(c, handler, handlerContext, traceId)) } else { - options.after?.(c, handler, handlerContext) + options.after?.(c, handler, handlerContext, traceId) } return res },