Skip to content

Commit afe10e7

Browse files
committed
Assert subscription field is not introspection.
1 parent cd273ad commit afe10e7

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

src/validation/__tests__/SingleFieldSubscriptionsRule-test.js

+28
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,32 @@ describe('Validate: Subscriptions with single field', () => {
8383
},
8484
]);
8585
});
86+
87+
it('fails with introspection field', () => {
88+
expectErrors(`
89+
subscription ImportantEmails {
90+
__typename
91+
}
92+
`).to.deep.equal([
93+
{
94+
message:
95+
'Subscription "ImportantEmails" must not select an introspection top level field.',
96+
locations: [{ line: 3, column: 9 }],
97+
},
98+
]);
99+
});
100+
101+
it('fails with introspection field in anonymous subscription', () => {
102+
expectErrors(`
103+
subscription {
104+
__typename
105+
}
106+
`).to.deep.equal([
107+
{
108+
message:
109+
'Anonymous Subscription must not select an introspection top level field.',
110+
locations: [{ line: 3, column: 9 }],
111+
},
112+
]);
113+
});
86114
});

src/validation/rules/SingleFieldSubscriptionsRule.js

+19-2
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@ import type { OperationDefinitionNode } from '../../language/ast';
66
import type { ASTValidationContext } from '../ValidationContext';
77

88
/**
9-
* Subscriptions must only include one field.
9+
* Subscriptions must only include a non-introspection field.
1010
*
11-
* A GraphQL subscription is valid only if it contains a single root field.
11+
* A GraphQL subscription is valid only if it contains a single root field and
12+
* that root field is not an introspection field.
1213
*/
1314
export function SingleFieldSubscriptionsRule(
1415
context: ASTValidationContext,
@@ -25,6 +26,22 @@ export function SingleFieldSubscriptionsRule(
2526
node.selectionSet.selections.slice(1),
2627
),
2728
);
29+
} else {
30+
const selection = node.selectionSet.selections[0];
31+
if (selection.kind === 'Field') {
32+
const fieldName = selection.name.value;
33+
// fieldName represents an introspection field if it starts with `__`
34+
if (fieldName[0] === '_' && fieldName[1] === '_') {
35+
context.reportError(
36+
new GraphQLError(
37+
node.name
38+
? `Subscription "${node.name.value}" must not select an introspection top level field.`
39+
: 'Anonymous Subscription must not select an introspection top level field.',
40+
node.selectionSet.selections,
41+
),
42+
);
43+
}
44+
}
2845
}
2946
}
3047
},

0 commit comments

Comments
 (0)