An Apollo Plugin for graphql-query-complexity
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
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) | |
} | |
}, | |
}), | |
} | |
} |
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
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