Skip to content

Commit

Permalink
feat: Make it possible to get the active span in the GraphQL resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
Karibash committed Dec 11, 2024
1 parent 5b73eb6 commit d359f99
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/clever-rice-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@envelop/sentry': minor
---

Make it possible to get the active span in the GraphQL resolver
43 changes: 43 additions & 0 deletions packages/plugins/sentry/__tests__/sentry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useSentry } from '@envelop/sentry';
import { assertSingleExecutionValue, createTestkit } from '@envelop/testing';
import { makeExecutableSchema } from '@graphql-tools/schema';
import * as Sentry from '@sentry/node';
import { Span } from '@sentry/types';
import '@sentry/tracing';

describe('sentry', () => {
Expand Down Expand Up @@ -252,4 +253,46 @@ describe('sentry', () => {
name: 'Error',
});
});

test('get the active span', async () => {
const { testkit: sentryTestkit, sentryTransport } = createSentryTestkit();
Sentry.init({
dsn: 'https://public@sentry.example.com/1',
transport: sentryTransport,
});

let activeSpan: Span | undefined;
const schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String!
}
`,
resolvers: {
Query: {
hello: async () => {
activeSpan = Sentry.getActiveSpan();
return 'Hello!';
},
},
},
});

const envelopTestkit = createTestkit([useSentry()], schema);
const result = await envelopTestkit.execute('{ hello }');
expect(result).toMatchInlineSnapshot(`
{
"data": {
"hello": "Hello!",
},
}
`);
expect(activeSpan).not.toBeUndefined();

// run sentry flush
await new Promise(res => setTimeout(res, 10));

const reports = sentryTestkit.reports();
expect(reports).toHaveLength(0);
});
});
5 changes: 4 additions & 1 deletion packages/plugins/sentry/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export const useSentry = <PluginContext extends Record<string, any> = {}>(
}

return {
onExecute({ args }) {
onExecute({ args, executeFn, setExecuteFn }) {
if (skipOperation(args)) {
return;
}
Expand Down Expand Up @@ -152,6 +152,9 @@ export const useSentry = <PluginContext extends Record<string, any> = {}>(
options.configureScope(args, Sentry.getCurrentScope());
}

// Give access to the span during resolvers execution
setExecuteFn(args => Sentry.withActiveSpan(rootSpan, () => executeFn(args)));

return {
onExecuteDone(payload) {
const handleResult: OnExecuteDoneHookResultOnNextHook<{}> = ({
Expand Down

0 comments on commit d359f99

Please sign in to comment.