Skip to content

Instantly share code, notes, and snippets.

@jorisvddonk
Last active October 9, 2022 23:01
Show Gist options
  • Save jorisvddonk/4768f1939449a43154ca1896a9eb6ccf to your computer and use it in GitHub Desktop.
Save jorisvddonk/4768f1939449a43154ca1896a9eb6ccf to your computer and use it in GitHub Desktop.
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

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