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:
parent
a507bc3e6c
commit
36267e21de
@ -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<string, any>) => void
|
||||
export type Hook = (
|
||||
c: Context,
|
||||
handler: Handler,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
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
|
||||
},
|
||||
|
Loading…
Reference in New Issue
Block a user