diff --git a/README.md b/README.md index c776174..43eaa89 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,9 @@ type ComplexityEstimatorArgs = { // The GraphQLField that is being evaluated field: GraphQLField, + // The GraphQL node that is being evaluated + node: FieldNode, + // The input arguments of the field args: {[key: string]: any}, diff --git a/src/QueryComplexity.ts b/src/QueryComplexity.ts index eda1605..2e112c2 100644 --- a/src/QueryComplexity.ts +++ b/src/QueryComplexity.ts @@ -33,6 +33,7 @@ import { export type ComplexityEstimatorArgs = { type: GraphQLCompositeType, field: GraphQLField, + node: FieldNode, args: {[key: string]: any}, childComplexity: number } @@ -250,6 +251,7 @@ export default class QueryComplexity { childComplexity, args, field, + node: childNode, type: typeDef }; const validScore = this.estimators.find(estimator => { diff --git a/src/__tests__/QueryComplexity-test.ts b/src/__tests__/QueryComplexity-test.ts index 882b072..5c87dfc 100644 --- a/src/__tests__/QueryComplexity-test.ts +++ b/src/__tests__/QueryComplexity-test.ts @@ -13,7 +13,7 @@ import {expect} from 'chai'; import schema from './fixtures/schema'; -import ComplexityVisitor, {getComplexity} from '../QueryComplexity'; +import ComplexityVisitor, {getComplexity, ComplexityEstimator} from '../QueryComplexity'; import { simpleEstimator, directiveEstimator, @@ -758,4 +758,30 @@ describe('QueryComplexity analysis', () => { }); expect(complexity).to.equal(41); // 1 for interface, 20 * 2 for complexScalar }); + + it('should include the current node in the estimator args', () => { + const ast = parse(` + query { + nonNullItem { + scalar + complexScalar + variableScalar(count: 10) + } + } + `); + + const fieldCountEstimator: ComplexityEstimator = ({ node }) => { + if (node.selectionSet) { + return 10 * node.selectionSet.selections.length; + } + return 0; + }; + + const complexity = getComplexity({ + estimators: [ fieldCountEstimator ], + schema, + query: ast + }); + expect(complexity).to.equal(30); // 3 fields on nonNullItem * 10 + }); });