From 81dd9b99f129f0779f99dabea380e271131984f1 Mon Sep 17 00:00:00 2001 From: HuyNQ Date: Fri, 11 Oct 2019 07:57:30 +0700 Subject: [PATCH] Skip complexity calculation by directiveEstimator when astNode is undefined --- src/__tests__/QueryComplexity-test.ts | 42 +++++++++++++++++++++++++++ src/__tests__/fixtures/schema.ts | 11 ++++++- src/estimators/directive/index.ts | 5 ++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/__tests__/QueryComplexity-test.ts b/src/__tests__/QueryComplexity-test.ts index b41842a..5c907cd 100644 --- a/src/__tests__/QueryComplexity-test.ts +++ b/src/__tests__/QueryComplexity-test.ts @@ -17,6 +17,7 @@ import schema from './fixtures/schema'; import ComplexityVisitor, {getComplexity} from '../QueryComplexity'; import { simpleEstimator, + directiveEstimator, fieldConfigEstimator, } from '../index'; @@ -321,4 +322,45 @@ describe('QueryComplexity analysis', () => { 'At least one complexity estimator has to return a complexity score.' ); }); + + it('should return NaN when no astNode available on field when use directiveEstimator', () => { + const ast = parse(` + query { + _service { + sdl + } + } + `); + + const complexity = getComplexity({ + estimators: [ + directiveEstimator(), + ], + schema, + query: ast + }); + expect(Number.isNaN(complexity)).to.equal(true); + }); + + it('should skip complexity calculation by directiveEstimator when no astNode available on field', () => { + const ast = parse(` + query { + _service { + sdl + } + } + `); + + const complexity = getComplexity({ + estimators: [ + directiveEstimator(), + simpleEstimator({ + defaultComplexity: 1 + }) + ], + schema, + query: ast + }); + expect(complexity).to.equal(2); + }); }); diff --git a/src/__tests__/fixtures/schema.ts b/src/__tests__/fixtures/schema.ts index 3c33507..9d9e982 100644 --- a/src/__tests__/fixtures/schema.ts +++ b/src/__tests__/fixtures/schema.ts @@ -83,6 +83,14 @@ const Union = new GraphQLUnionType({ resolveType: () => Item }); +const SDLInterface = new GraphQLInterfaceType({ + name: 'SDLInterface', + fields: { + sdl: { type: GraphQLString } + }, + resolveType: () => '"SDL"' +}); + const Query = new GraphQLObjectType({ name: 'Query', fields: () => ({ @@ -126,7 +134,8 @@ const Query = new GraphQLObjectType({ type: new GraphQLNonNull(GraphQLInt) } } - } + }, + _service: {type: SDLInterface}, }), }); diff --git a/src/estimators/directive/index.ts b/src/estimators/directive/index.ts index 0bfa860..ae9c19b 100644 --- a/src/estimators/directive/index.ts +++ b/src/estimators/directive/index.ts @@ -28,6 +28,11 @@ export default function (options?: {}): ComplexityEstimator { }); return (args: ComplexityEstimatorArgs) => { + // Ignore if astNode is undefined + if (!args.field.astNode) { + return; + } + const values = getDirectiveValues(directive, args.field.astNode); // Ignore if no directive set