Skip to content

fix: cost-limit ignore only Field Node named __schema #772

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 3 commits into from
Apr 18, 2025
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
7 changes: 6 additions & 1 deletion packages/plugins/cost-limit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ class CostLimitVisitor {
node: FieldNode | FragmentDefinitionNode | InlineFragmentNode | OperationDefinitionNode | FragmentSpreadNode,
depth = 0,
): number {
if (this.config.ignoreIntrospection && 'name' in node && node.name?.value === '__schema') {
if (
this.config.ignoreIntrospection &&
'name' in node &&
node.name?.value === '__schema' &&
node.kind === Kind.FIELD
) {
return 0;
}

Expand Down
63 changes: 63 additions & 0 deletions packages/plugins/cost-limit/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,68 @@ describe('costLimitPlugin', () => {
]);
});

it('should limit cost for query named `__schema`', async () => {
const testkit = createTestkit(
[
costLimitPlugin({
maxCost: 10,
objectCost: 4,
scalarCost: 2,
depthCostFactor: 2,
ignoreIntrospection: true,
}),
],
schema,
);
const result = await testkit.execute(`
query __schema {
books {
title
author
}
}
`);

assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.map((error) => error.message)).toEqual([
'Syntax Error: Query Cost limit of 10 exceeded, found 12.',
]);
});

it('should limit cost for fragment named `__schema`', async () => {
const testkit = createTestkit(
[
costLimitPlugin({
maxCost: 10,
objectCost: 4,
scalarCost: 2,
depthCostFactor: 2,
ignoreIntrospection: true,
}),
],
schema,
);
const result = await testkit.execute(`
query {
...__schema
}

fragment __schema on Query {
books {
title
author
}
}
`);

assertSingleExecutionValue(result);
expect(result.errors).toBeDefined();
expect(result.errors?.map((error) => error.message)).toEqual([
'Syntax Error: Query Cost limit of 10 exceeded, found 58.',
]);
});

it('should allow introspection', async () => {
const testkit = createTestkit(
[
Expand All @@ -100,6 +162,7 @@ describe('costLimitPlugin', () => {
],
schema,
);
const x = getIntrospectionQuery();
const result = await testkit.execute(getIntrospectionQuery());

assertSingleExecutionValue(result);
Expand Down