Skip to content

Commit 78eeda6

Browse files
committed
feat(tracing): add operation name to graphql error metrics
1 parent 7b3ca22 commit 78eeda6

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

src/index.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@ import mercurius, { MercuriusError } from 'mercurius';
1313
import MercuriusGQLUpload from 'mercurius-upload';
1414
import MercuriusCache from 'mercurius-cache';
1515
import proxy, { type FastifyHttpProxyOptions } from '@fastify/http-proxy';
16-
import { NoSchemaIntrospectionCustomRule } from 'graphql';
16+
import {
17+
Kind,
18+
NoSchemaIntrospectionCustomRule,
19+
type OperationDefinitionNode,
20+
} from 'graphql';
1721

1822
import './config';
1923

@@ -249,6 +253,8 @@ export default async function app(
249253
if (typeof newError.extensions?.code === 'string') {
250254
counters?.api?.graphqlErrors?.add(1, {
251255
'graphql.error.code': newError.extensions.code,
256+
'graphql.operation.name':
257+
ctx?.graphqlOperationName || 'unknown',
252258
});
253259
}
254260

@@ -281,6 +287,22 @@ export default async function app(
281287
},
282288
});
283289

290+
app.register(async (instance) => {
291+
instance.graphql.addHook(
292+
'preValidation',
293+
async (_schema, document, context) => {
294+
const operations = document.definitions.filter(
295+
(d): d is OperationDefinitionNode =>
296+
d.kind === Kind.OPERATION_DEFINITION,
297+
);
298+
299+
if (operations.length === 1) {
300+
context.graphqlOperationName = operations[0].name?.value;
301+
}
302+
},
303+
);
304+
});
305+
284306
if (isProd) {
285307
app.register(MercuriusCache, {
286308
ttl: 10,

src/types.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,12 @@ declare module 'fastify' {
124124
}
125125
}
126126

127+
declare module 'mercurius' {
128+
interface MercuriusContext {
129+
graphqlOperationName?: string;
130+
}
131+
}
132+
127133
type IgnoredTypes = Promise<unknown> | ((...args: unknown[]) => unknown);
128134

129135
export type ChangeObject<Type> = {

0 commit comments

Comments
 (0)