Skip to content

Instantly share code, notes, and snippets.

@reconbot
Last active September 17, 2024 13:33
Show Gist options
  • Save reconbot/37ccd8b8fcdfb78ff6a16a7055edf103 to your computer and use it in GitHub Desktop.
Save reconbot/37ccd8b8fcdfb78ff6a16a7055edf103 to your computer and use it in GitHub Desktop.
An Apollo Plugin for graphql-query-complexity
import { ComplexityEstimator, getComplexity } from 'graphql-query-complexity'
import { GraphQLError, GraphQLSchema, separateOperations } from 'graphql'
import { PluginDefinition } from 'apollo-server-core'
export const createComplexityPlugin = ({
schema,
maximumComplexity,
estimators,
onComplete,
createError = (max, actual) => { throw new GraphQLError(`Query too complex. Value of ${actual} is over the maximum ${max}.`) },
}: {
schema: GraphQLSchema;
maximumComplexity: number;
estimators: Array<ComplexityEstimator>;
onComplete?: (complexity: number) => void;
createError?: (max: number, actual: number) => GraphQLError;
}): PluginDefinition => {
return {
requestDidStart: () => ({
didResolveOperation({ request, document }) {
const query = request.operationName
? separateOperations(document)[request.operationName]
: document
const complexity = getComplexity({
schema,
query,
variables: request.variables,
estimators,
})
if (complexity >= maximumComplexity) {
createError(maximumComplexity, complexity)
}
if (onComplete) {
onComplete(complexity)
}
},
}),
}
}
import { createComplexityPlugin } from './createComplexityPlugin'
import { ApolloServer } from 'apollo-server-lambda'
import { schema } from './schema'
import { fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity'
export const buildServer = () => {
return new ApolloServer({
schema,
plugins: [
createComplexityPlugin({
schema,
estimators: [
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
],
maximumComplexity: 1000,
onComplete: (complexity) => {
console.log('Query Complexity:', complexity)
},
}),
],
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment