0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-22 02:27:49 +01:00

feat(middleware/hook): assign traceId to each request

This commit is contained in:
Taku Amano 2024-06-23 22:36:27 +09:00
parent a507bc3e6c
commit 36267e21de

View File

@ -3,8 +3,13 @@ import type { Env, Handler, MiddlewareHandler, Next } from '../../types'
const isWrapped = Symbol()
export type Hook = (
c: Context,
handler: Handler,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Hook = (c: Context, handler: Handler, handlerContext: Record<string, any>) => void
handlerContext: Record<string, any>,
traceId: string
) => void
export const hook = <E extends Env = Env>(
options: {
before?: Hook
@ -14,6 +19,9 @@ export const hook = <E extends Env = Env>(
} = {}
): MiddlewareHandler => {
function hook(c: Context<E>, 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 = <E extends Env = Env>(
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
},