|
| 1 | +// We import these types from `withSentry` rather than directly from `next` because our version can work simultaneously |
| 2 | +// with multiple versions of next. See note in `withSentry` for more. |
| 3 | +import type { NextApiHandler, WrappedNextApiHandler } from '../../utils/withSentry'; |
| 4 | +import { withSentry } from '../../utils/withSentry'; |
| 5 | + |
| 6 | +/** |
| 7 | + * TODO |
| 8 | + */ |
| 9 | +export function withSentryAPI( |
| 10 | + maybeWrappedHandler: NextApiHandler | WrappedNextApiHandler, |
| 11 | + parameterizedRoute: string, |
| 12 | +): WrappedNextApiHandler { |
| 13 | + // We want the innards of `withSentry` to have access to the parameterized route, so it can be used when we start the |
| 14 | + // request transaction. If we were always the ones calling `withSentry` (the way we're always the ones to call |
| 15 | + // `withSentryServerSideProps`, for example), then we could just pass it in as a second parameter and know it would |
| 16 | + // always be there. But in the case where users have already manually wrapped their API route handlers with |
| 17 | + // `withSentry`, they're the ones calling it, without the parameterized route as a second parameter. We need a |
| 18 | + // different way to make it available. |
| 19 | + // |
| 20 | + // Fortunately, with some clever `this` usage, we can do it. |
| 21 | + |
| 22 | + // First we add it as a property on the exported handler. |
| 23 | + maybeWrappedHandler.__sentry_route__ = parameterizedRoute; |
| 24 | + |
| 25 | + // TODO: Finish explanation |
| 26 | + // TODO: Figure out if `maybeWrappedHandler` is `withSentry` itself or the results of calling `withSentry` on the original handler |
| 27 | + |
| 28 | + if ('__sentry_wrapped__' in maybeWrappedHandler) { |
| 29 | + return wrapLite(maybeWrappedHandler); |
| 30 | + } |
| 31 | + |
| 32 | + return withSentry(maybeWrappedHandler); |
| 33 | +} |
| 34 | + |
| 35 | +// TODO: This needs a better name, and a docstring |
| 36 | +function wrapLite(alreadyWrappedHandler: WrappedNextApiHandler): WrappedNextApiHandler { |
| 37 | + const newWrapper: WrappedNextApiHandler = (req, res) => { |
| 38 | + // Make `alreadyWrappedHandler` its own `this` |
| 39 | + return alreadyWrappedHandler.call(alreadyWrappedHandler, req, res); |
| 40 | + }; |
| 41 | + |
| 42 | + return newWrapper; |
| 43 | +} |
0 commit comments