import type { ApolloServerPlugin } from 'apollo-server-plugin-base' ; import { getComplexity , simpleEstimator , fieldExtensionsEstimator } from 'graphql-query-complexity' ; import { separateOperations , GraphQLSchema } from 'graphql' ; export function queryCostPlugin ( opts ) { return { requestDidStart : ( { context } ) => { let complexity = 0 ; const maxComplexity = ( typeof opts . maxComplexity === 'string' ? parseInt ( opts . maxComplexity ) : opts . maxComplexity ) || 100000 ; return { 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.` ) ; } } , willSendResponse ( { response } ) { response . extensions = response . extensions || { } ; response . extensions . complexity = complexity ; response . extensions . maxComplexity = maxComplexity ; } , } ; } , } as ApolloServerPlugin ; }