(
handler: Handler<TEvent, TResult> | StreamifyHandler<TEvent, TResult>,
wrapOptions: Partial<WrapperOptions> = {},
)
| 163 | * @returns Handler |
| 164 | */ |
| 165 | export function wrapHandler<TEvent, TResult>( |
| 166 | handler: Handler<TEvent, TResult> | StreamifyHandler<TEvent, TResult>, |
| 167 | wrapOptions: Partial<WrapperOptions> = {}, |
| 168 | ): Handler<TEvent, TResult> | StreamifyHandler<TEvent, TResult> { |
| 169 | const START_TIME = performance.now(); |
| 170 | |
| 171 | // eslint-disable-next-line typescript/no-deprecated |
| 172 | if (typeof wrapOptions.startTrace !== 'undefined') { |
| 173 | consoleSandbox(() => { |
| 174 | // eslint-disable-next-line no-console |
| 175 | console.warn( |
| 176 | 'The `startTrace` option is deprecated and will be removed in a future major version. If you want to disable tracing, set `SENTRY_TRACES_SAMPLE_RATE` to `0.0`.', |
| 177 | ); |
| 178 | }); |
| 179 | } |
| 180 | |
| 181 | const options: WrapperOptions = { |
| 182 | flushTimeout: 2000, |
| 183 | callbackWaitsForEmptyEventLoop: false, |
| 184 | captureTimeoutWarning: true, |
| 185 | timeoutWarningLimit: 500, |
| 186 | captureAllSettledReasons: false, |
| 187 | startTrace: true, // TODO(v11): Remove this option. Set to true here to satisfy the type, but has no effect. |
| 188 | ...wrapOptions, |
| 189 | }; |
| 190 | |
| 191 | if (isStreamingHandler(handler)) { |
| 192 | return wrapStreamingHandler(handler, options, START_TIME); |
| 193 | } |
| 194 | |
| 195 | let timeoutWarningTimer: NodeJS.Timeout | undefined; |
| 196 | |
| 197 | // AWSLambda is like Express. It makes a distinction about handlers based on its last argument |
| 198 | // async (event) => async handler |
| 199 | // async (event, context) => async handler |
| 200 | // (event, context, callback) => sync handler |
| 201 | // Nevertheless whatever option is chosen by user, we convert it to async handler. |
| 202 | const asyncHandler: AsyncHandler<Handler<TEvent, TResult>> = |
| 203 | handler.length > 2 |
| 204 | ? (event, context) => |
| 205 | new Promise((resolve, reject) => { |
| 206 | const rv = (handler as SyncHandler<Handler<TEvent, TResult>>)(event, context, (error, result) => { |
| 207 | if (error === null || error === undefined) { |
| 208 | resolve(result!); // eslint-disable-line @typescript-eslint/no-non-null-assertion |
| 209 | } else { |
| 210 | reject(error); |
| 211 | } |
| 212 | }) as unknown; |
| 213 | |
| 214 | // This should never happen, but still can if someone writes a handler as |
| 215 | // `async (event, context, callback) => {}` |
| 216 | if (isPromise(rv)) { |
| 217 | void (rv as Promise<NonNullable<TResult>>).then(resolve, reject); |
| 218 | } |
| 219 | }) |
| 220 | : (handler as AsyncHandler<Handler<TEvent, TResult>>); |
| 221 | |
| 222 | return async (event: TEvent, context: Context) => { |
no test coverage detected