|
| 1 | +import { Hub } from '@sentry/hub'; |
| 2 | +import { EventProcessor, Integration } from '@sentry/types'; |
| 3 | +import { fill, isThenable, loadModule, logger } from '@sentry/utils'; |
| 4 | + |
| 5 | +import { IS_DEBUG_BUILD } from '../../flags'; |
| 6 | + |
| 7 | +interface PrismaClient { |
| 8 | + prototype: { |
| 9 | + query: () => void | Promise<unknown>; |
| 10 | + }; |
| 11 | +} |
| 12 | + |
| 13 | +/** Tracing integration for @prisma/client package */ |
| 14 | +export class Prisma implements Integration { |
| 15 | + /** |
| 16 | + * @inheritDoc |
| 17 | + */ |
| 18 | + public static id: string = 'Prisma'; |
| 19 | + |
| 20 | + /** |
| 21 | + * @inheritDoc |
| 22 | + */ |
| 23 | + public name: string = Prisma.id; |
| 24 | + |
| 25 | + /** |
| 26 | + * @inheritDoc |
| 27 | + */ |
| 28 | + public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { |
| 29 | + const pkg = loadModule<{ PrismaClient: PrismaClient }>('@prisma/client'); |
| 30 | + |
| 31 | + if (!pkg) { |
| 32 | + IS_DEBUG_BUILD && logger.error('Prisma integration was unable to require `@prisma/client` package.'); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + fill(pkg.PrismaClient.prototype, '_executeRequest', function (orig: () => void | Promise<unknown>) { |
| 37 | + return function (this: unknown, config: unknown) { |
| 38 | + const scope = getCurrentHub().getScope(); |
| 39 | + const parentSpan = scope?.getSpan(); |
| 40 | + const span = parentSpan?.startChild({ |
| 41 | + description: typeof config === 'string' ? config : (config as { clientMethod: string }).clientMethod, |
| 42 | + op: 'db', |
| 43 | + }); |
| 44 | + |
| 45 | + const rv = orig.call(this, config); |
| 46 | + |
| 47 | + if (isThenable(rv)) { |
| 48 | + return rv.then((res: unknown) => { |
| 49 | + span?.finish(); |
| 50 | + return res; |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + span?.finish(); |
| 55 | + return rv; |
| 56 | + }; |
| 57 | + }); |
| 58 | + } |
| 59 | +} |
0 commit comments