|
| 1 | +import type { AppLoadContext, EntryContext } from 'react-router'; |
| 2 | +import { SENTRY_PARAMETERIZED_ROUTE } from './attributes'; |
| 3 | +import { getRootSpan, getActiveSpan } from '@sentry/core'; |
| 4 | + |
| 5 | +type OriginalHandleRequest = ( |
| 6 | + request: Request, |
| 7 | + responseStatusCode: number, |
| 8 | + responseHeaders: Headers, |
| 9 | + routerContext: EntryContext, |
| 10 | + loadContext: AppLoadContext, |
| 11 | +) => Promise<unknown>; |
| 12 | + |
| 13 | +/** |
| 14 | + * Wraps the original handleRequest function to add Sentry instrumentation. |
| 15 | + * |
| 16 | + * @param originalHandle - The original handleRequest function to wrap |
| 17 | + * @returns A wrapped version of the handle request function with Sentry instrumentation |
| 18 | + */ |
| 19 | +export function sentryHandleRequest(originalHandle: OriginalHandleRequest): OriginalHandleRequest { |
| 20 | + return async function sentryInstrumentedHandleRequest( |
| 21 | + request: Request, |
| 22 | + responseStatusCode: number, |
| 23 | + responseHeaders: Headers, |
| 24 | + routerContext: EntryContext, |
| 25 | + loadContext: AppLoadContext, |
| 26 | + ) { |
| 27 | + const parameterizedPath = |
| 28 | + routerContext?.staticHandlerContext?.matches?.[routerContext.staticHandlerContext.matches.length - 1]?.route.path; |
| 29 | + if (parameterizedPath) { |
| 30 | + const activeSpan = getActiveSpan(); |
| 31 | + if (activeSpan) { |
| 32 | + const rootSpan = getRootSpan(activeSpan); |
| 33 | + rootSpan.setAttribute(SENTRY_PARAMETERIZED_ROUTE, parameterizedPath); |
| 34 | + } |
| 35 | + } |
| 36 | + return originalHandle(request, responseStatusCode, responseHeaders, routerContext, loadContext); |
| 37 | + }; |
| 38 | +} |
0 commit comments