Skip to content

Commit

Permalink
fix: add missing operationName (#3488)
Browse files Browse the repository at this point in the history
Co-authored-by: Tomas Kroupa <[email protected]>
  • Loading branch information
kroupacz and Tomas Kroupa authored Nov 26, 2024
1 parent f2255d2 commit a4bc07f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/changelog1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@graphql-yoga/plugin-apollo-usage-report": patch
---

fixed: move logic from `onEnveloped` hook to `onParse` hook (`onParseEnd`) which prevents the `operationName` could be missing.
42 changes: 27 additions & 15 deletions packages/plugins/apollo-usage-report/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { printSchema, stripIgnoredCharacters } from 'graphql';
import { DocumentNode, getOperationAST, Kind, printSchema, stripIgnoredCharacters } from 'graphql';
import {
isAsyncIterable,
Maybe,
Expand Down Expand Up @@ -134,21 +134,26 @@ export function useApolloUsageReport(options: ApolloUsageReportOptions = {}): Pl
}
},

onEnveloped({ context }) {
if (!context) {
return;
}
const ctx = ctxForReq.get(context.request)?.traces.get(context);
if (!ctx) {
logger.debug('operation tracing context not found, this operation will not be traced.');
return;
}
onParse() {
return function onParseEnd({ result, context }) {
const ctx = ctxForReq.get(context.request)?.traces.get(context);
if (!ctx) {
logger.debug(
'operation tracing context not found, this operation will not be traced.',
);
return;
}

const operationName =
context.params.operationName ??
(isDocumentNode(result) ? getOperationAST(result)?.name?.value : undefined);
const signature = context.params.query
? stripIgnoredCharacters(context.params.query)
: '';

const signature = context.params.query
? stripIgnoredCharacters(context.params.query)
: '';
ctx.operationKey = `# ${context.params.operationName || '-'}\n${signature}`;
ctx.schemaId = schemaId;
ctx.operationKey = `# ${operationName || '-'}\n${signature}`;
ctx.schemaId = schemaId;
};
},

onResultProcess({ request, result, serverContext }) {
Expand Down Expand Up @@ -271,3 +276,10 @@ async function sendTrace(
logger.error('Failed to send trace:', err);
}
}

function isDocumentNode(data: unknown): data is DocumentNode {
const isObject = (data: unknown): data is Record<string, unknown> =>
!!data && typeof data === 'object';

return isObject(data) && data.kind === Kind.DOCUMENT;
}

0 comments on commit a4bc07f

Please sign in to comment.