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})`,
);
}
}
};
}
}
@simplenotezy
Copy link

simplenotezy commented Oct 9, 2022

Does't seem to work in latest version of Nestjs/graphql.

Module '"graphql-query-complexity"' has no exported member 'fieldConfigEstimator'. Did you mean to use 'import fieldConfigEstimator from "graphql-query-complexity"' instead?ts(2614)

And

Property 'requestDidStart' in type 'ApolloComplexityPlugin' is not assignable to the same property in base type 'ApolloServerPlugin<BaseContext>'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment