GraphQL query complexity analysis and validation for graphql-js
GraphQL query complexity analysis and validation for graphql-js
This library provides GraphQL query analysis to reject complex queries to your GraphQL server. It can be used to protect your GraphQL servers against resource exhaustion and DoS attacks.
This library was originally developed as part of the Slicknode GraphQL Framework + Headless CMS.
Works with graphql-js reference implementation.
Install the package via npm
npm install -S graphql-query-complexityCreate the rule with a maximum query complexity:
…The complexity calculation of a GraphQL query can be customized with so called complexity estimators. A complexity estimator is a simple function that calculates the complexity for a field. You can add any number of complexity estimators to the rule, which are then executed one after another. The first estimator that returns a numeric complexity value determines the complexity for that field.
At least one estimator has to return a complexity value, otherwise an exception is raised. You can for example use the simpleEstimator as the last estimator in your chain to define a default value.
You can use any of the available estimators to calculate the complexity of a field or write your own:
simpleEstimator: The simple estimator returns a fixed complexity for each field. Can be used as
last estimator in the chain for a default value.directiveEstimator: Set the complexity via a directive in your
schema definition (for example via GraphQL SDL)fieldExtensionsEstimator: The field extensions estimator lets you set a numeric value or a custom estimator
function in the field config extensions of your schema.Consult the documentation of each estimator for information about how to use them.
An estimator has the following function signature:
…To use the query complexity analysis validation rule with express-graphql, use something like the following:
…If you want to calculate the complexity of a GraphQL query outside of the validation phase, for example to
return the complexity value in a resolver, you can calculate the complexity via getComplexity:
…This project is inspired by the following prior projects:
No open issues yet, or sync has not completed.