Last active
September 13, 2018 09:17
-
-
Save ddombrow/fe8d3765e7971001ec7af426eb9a7a6f to your computer and use it in GitHub Desktop.
New Relic GraphQL extension.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
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
This looks perfect, thanks!