Last active
October 9, 2022 23:01
-
-
Save jorisvddonk/4768f1939449a43154ca1896a9eb6ccf to your computer and use it in GitHub Desktop.
ApolloComplexityPlugin
This file contains 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
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
Does't seem to work in latest version of Nestjs/graphql.
And