Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ApolloComplexityPlugin
import { ApolloServerPlugin, GraphQLServiceContext } from "apollo-server-plugin-base";
import { GraphQLSchema, separateOperations } from "graphql";
import { fieldConfigEstimator, getComplexity, simpleEstimator } from "graphql-query-complexity";
export class ApolloComplexityPlugin implements ApolloServerPlugin {
private schema: GraphQLSchema;
constructor(private maxComplexity: number) { }
public serverWillStart(service: GraphQLServiceContext) {
this.schema = service.schema;
}
public requestDidStart() {
return {
didResolveOperation: ({ request, document }) => {
const complexity = getComplexity({
schema: this.schema, query: request.operationName
? separateOperations(document)[request.operationName]
: document, variables: request.variables, estimators: [
fieldConfigEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
]
});
if (complexity > this.maxComplexity) {
throw new Error(
`Sorry, too complicated query (complexity: ${complexity}, max complexity: ${this.maxComplexity})`,
);
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.