Skip to content

Instantly share code, notes, and snippets.

@danstarns
Last active April 5, 2025 14:16
Show Gist options
  • Select an option

  • Save danstarns/72588e9762c0c45f739538cfa6fddbb3 to your computer and use it in GitHub Desktop.

Select an option

Save danstarns/72588e9762c0c45f739538cfa6fddbb3 to your computer and use it in GitHub Desktop.
graphql-depth-apollo-server
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;
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