From 4be85d899b4f91594ae3a975795a38a6854bfdfc Mon Sep 17 00:00:00 2001 From: Bas Kiers Date: Tue, 19 Sep 2023 14:11:31 +0200 Subject: [PATCH] fix: default non-defined graphql operations to have 0 complexity --- src/QueryComplexity.ts | 8 ++++++-- src/__tests__/QueryComplexity-test.ts | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/QueryComplexity.ts b/src/QueryComplexity.ts index 41dee1e..1175e9b 100644 --- a/src/QueryComplexity.ts +++ b/src/QueryComplexity.ts @@ -238,9 +238,13 @@ export default class QueryComplexity { | FragmentDefinitionNode | InlineFragmentNode | OperationDefinitionNode, - typeDef: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType + typeDef: + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | undefined ): number { - if (node.selectionSet) { + if (node.selectionSet && typeDef) { let fields: GraphQLFieldMap = {}; if ( typeDef instanceof GraphQLObjectType || diff --git a/src/__tests__/QueryComplexity-test.ts b/src/__tests__/QueryComplexity-test.ts index 92269dd..b33e371 100644 --- a/src/__tests__/QueryComplexity-test.ts +++ b/src/__tests__/QueryComplexity-test.ts @@ -891,4 +891,25 @@ describe('QueryComplexity analysis', () => { expect(errors).to.have.length(1); expect(errors[0].message).to.contain('INVALIDVALUE'); }); + + it('falls back to 0 complexity for GraphQL operations not supported by the schema', () => { + const ast = parse(` + subscription { + foo + } + `); + + const errors = validate(schema, ast, [ + createComplexityRule({ + maximumComplexity: 1000, + estimators: [ + simpleEstimator({ + defaultComplexity: 1, + }), + ], + }), + ]); + + expect(errors).to.have.length(0); + }); });