Last active
April 5, 2025 14:16
-
-
Save danstarns/72588e9762c0c45f739538cfa6fddbb3 to your computer and use it in GitHub Desktop.
graphql-depth-apollo-server
This file contains hidden or 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 gqlComplexity = require("graphql-query-complexity"); | |
| const { UserInputError } = require("apollo-server"); | |
| const { separateOperations } = require("graphql"); | |
| const MAX_DEPTH = 10; | |
| const estimators = [ | |
| gqlComplexity.fieldExtensionsEstimator(), | |
| gqlComplexity.directiveEstimator(), | |
| gqlComplexity.simpleEstimator({ defaultComplexity: 1 }) | |
| ]; | |
| /* This stops someone making a query more complex than MAX_DEPTH levels deep, ensures that | |
| the server does not receive Denial-of-service attack from its users 😱 | |
| */ | |
| function complexity(schema) { | |
| return { | |
| requestDidStart: () => ({ | |
| didResolveOperation({ request, document }) { | |
| const { operationName, variables } = request; | |
| const query = operationName | |
| ? separateOperations(document)[operationName] | |
| : document; | |
| const depth = gqlComplexity.getComplexity({ | |
| schema, | |
| query, | |
| variables, | |
| estimators | |
| }); | |
| if (depth >= MAX_DEPTH) { | |
| throw new UserInputError( | |
| `Too complicated query! ${depth} is over ${MAX_DEPTH} that is the max allowed complexity.` | |
| ); | |
| } | |
| } | |
| }) | |
| }; | |
| } | |
| module.exports = complexity; |
This file contains hidden or 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 path = require("path"); | |
| const { ApolloServer } = require("apollo-server"); | |
| const schema = require("./schema.js"); // not included in this gist | |
| const complexity = require("./complexity.js"); | |
| const server = new ApolloServer({ | |
| schema, | |
| plugins: [complexity(schema)] | |
| }); | |
| module.exports = server; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment