Skip to content

Include meta fields (__typename, __type, __schema) against total field complexity [2] #92

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/QueryComplexity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ import {
Kind,
getNamedType,
GraphQLError,
SchemaMetaFieldDef,
TypeMetaFieldDef,
TypeNameMetaFieldDef,
} from 'graphql';

export type ComplexityEstimatorArgs = {
Expand Down Expand Up @@ -307,7 +310,23 @@ export default class QueryComplexity {

switch (childNode.kind) {
case Kind.FIELD: {
const field = fields[childNode.name.value];
let field = null;

switch (childNode.name.value) {
case SchemaMetaFieldDef.name:
field = SchemaMetaFieldDef;
break;
case TypeMetaFieldDef.name:
field = TypeMetaFieldDef;
break;
case TypeNameMetaFieldDef.name:
field = TypeNameMetaFieldDef;
break;
default:
field = fields[childNode.name.value];
break;
}

// Invalid field, should be caught by other validation rules
if (!field) {
break;
Expand Down
27 changes: 27 additions & 0 deletions src/__tests__/QueryComplexity-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,33 @@ describe('QueryComplexity analysis', () => {
expect(complexity2).to.equal(20);
});

it('should calculate complexity for meta fields', () => {
const query = parse(`
query Primary {
__typename
__type(name: "Primary") {
name
}
__schema {
types {
name
}
}
}
`);

const complexity = getComplexity({
estimators: [
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
],
schema,
query,
});

expect(complexity).to.equal(6);
});

it('should calculate max complexity for fragment on union type', () => {
const query = parse(`
query Primary {
Expand Down