import { ApolloServerPlugin } from 'apollo-server-plugin-base' ; import { getComplexity , simpleEstimator , fieldExtensionsEstimator } from 'graphql-query-complexity' ; import { separateOperations , GraphQLSchema } from 'graphql' ; export function initQueryComplexityPlugin ( opts ) { return { async requestDidStart ( ) { let complexity = 0 ; const maxComplexity = opts . maxComplexity || 10000 ; return { async didResolveOperation ( { request , document } ) { /**
                     * This provides GraphQL query analysis to be able to react on complex queries to your GraphQL server.
                     * This can be used to protect your GraphQL servers against resource exhaustion and DoS attacks.
                     * More documentation can be found at https://github.com/ivome/graphql-query-complexity.
                     */ complexity = getComplexity ( { schema : opts . schema , query : request . operationName ? separateOperations ( document ) [ request . operationName ] : document , variables : request . variables , estimators : [ fieldExtensionsEstimator ( ) , simpleEstimator ( { defaultComplexity : 1 } ) , ] , } ) ; if ( complexity >= maxComplexity ) { throw new Error ( `Sorry, too complicated query! ${ complexity } is over ${ maxComplexity } that is the max allowed complexity.` ) ; } if ( request . operationName !== 'IntrospectionQuery' ) { console . log ( `Used query ${ request . operationName || '' } complexity points: ${ complexity }` ) ; } } , async willSendResponse ( { response } ) { response . extensions = response . extensions || { } ; response . extensions . complexity = complexity ; response . extensions . maxComplexity = maxComplexity ; } , } ; } , } ; }