Skip to content

Commit 9eb9d11

Browse files
committed
Skip complexity calculation by directiveEstimator when astNode is undefined
1 parent fdf7814 commit 9eb9d11

File tree

3 files changed

+57
-1
lines changed

3 files changed

+57
-1
lines changed

src/__tests__/QueryComplexity-test.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import schema from './fixtures/schema';
1717
import ComplexityVisitor, {getComplexity} from '../QueryComplexity';
1818
import {
1919
simpleEstimator,
20+
directiveEstimator,
2021
fieldConfigEstimator,
2122
} from '../index';
2223

@@ -321,4 +322,45 @@ describe('QueryComplexity analysis', () => {
321322
'At least one complexity estimator has to return a complexity score.'
322323
);
323324
});
325+
326+
it.only('should return NaN when no astNode available on field when use directiveEstimator', () => {
327+
const ast = parse(`
328+
query {
329+
_service {
330+
sdl
331+
}
332+
}
333+
`);
334+
335+
const complexity = getComplexity({
336+
estimators: [
337+
directiveEstimator(),
338+
],
339+
schema,
340+
query: ast
341+
});
342+
expect(Number.isNaN(complexity)).to.equal(true);
343+
});
344+
345+
it.only('should skip complexity calculation by directiveEstimator when no astNode available on field', () => {
346+
const ast = parse(`
347+
query {
348+
_service {
349+
sdl
350+
}
351+
}
352+
`);
353+
354+
const complexity = getComplexity({
355+
estimators: [
356+
directiveEstimator(),
357+
simpleEstimator({
358+
defaultComplexity: 1
359+
})
360+
],
361+
schema,
362+
query: ast
363+
});
364+
expect(complexity).to.equal(2);
365+
});
324366
});

src/__tests__/fixtures/schema.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,14 @@ const Union = new GraphQLUnionType({
8383
resolveType: () => Item
8484
});
8585

86+
const SDLInterface = new GraphQLInterfaceType({
87+
name: 'SDLInterface',
88+
fields: {
89+
sdl: { type: GraphQLString }
90+
},
91+
resolveType: () => '"SDL"'
92+
});
93+
8694
const Query = new GraphQLObjectType({
8795
name: 'Query',
8896
fields: () => ({
@@ -126,7 +134,8 @@ const Query = new GraphQLObjectType({
126134
type: new GraphQLNonNull(GraphQLInt)
127135
}
128136
}
129-
}
137+
},
138+
_service: {type: SDLInterface},
130139
}),
131140
});
132141

src/estimators/directive/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ export default function (options?: {}): ComplexityEstimator {
2828
});
2929

3030
return (args: ComplexityEstimatorArgs) => {
31+
// Ignore if astNode is undefined
32+
if (!args.field.astNode) {
33+
return;
34+
}
35+
3136
const values = getDirectiveValues(directive, args.field.astNode);
3237

3338
// Ignore if no directive set

0 commit comments

Comments
 (0)