Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
New Relic GraphQL extension.
const { GraphQLExtension } = require("graphql-extensions");
const newrelic = require("newrelic");
function traceSummary(trace) {
if (!trace) {
return "No trace data.";
}
try {
const { duration, execution: {resolvers}} = trace;
const summary = [];
summary.push(`Total Duration (ms): ${duration / 1000000}`);
const rootResolverTimings = resolvers
.filter(r => (r.parentType === "RootQuery"))
.map(r => (`Field: ${r.fieldName} - ReturnType: ${r.returnType} - Duration: ${ r.duration / 1000000 }`));
summary.push(...rootResolverTimings);
return summary.join(" | ");
}
catch(err) {
return "Error getting trace summary.";
}
}
class NewRelicExtension extends GraphQLExtension {
constructor() {
super();
}
requestDidStart({queryString, operationName, variables, persistedQueryHit}) {
newrelic.setTransactionName(`graphql (${operationName})`);
newrelic.addCustomAttribute("gqlQuery", queryString);
newrelic.addCustomAttribute("gqlVars", variables);
newrelic.addCustomAttribute("persistedQueryHit", persistedQueryHit);
return;
}
willSendResponse(payload) {
newrelic.addCustomAttribute("traceSummary", traceSummary(payload.graphqlResponse
&& payload.graphqlResponse.extensions
&& payload.graphqlResponse.extensions.tracing));
}
}
module.exports = NewRelicExtension;
@localshred

This comment has been minimized.

Copy link

@localshred localshred commented Aug 24, 2018

This looks perfect, thanks!

@localshred

This comment has been minimized.

Copy link

@localshred localshred commented Sep 13, 2018

I repurposed this a bit and published it as an NPM package for anyone interested https://github.com/localshred/apollo-newrelic-extension

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment