Skip to content

Commit

Permalink
Assert subscription field is not introspection.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjie committed Nov 25, 2020
1 parent cd273ad commit afe10e7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
28 changes: 28 additions & 0 deletions src/validation/__tests__/SingleFieldSubscriptionsRule-test.js
Expand Up @@ -83,4 +83,32 @@ describe('Validate: Subscriptions with single field', () => {
},
]);
});

it('fails with introspection field', () => {
expectErrors(`
subscription ImportantEmails {
__typename
}
`).to.deep.equal([
{
message:
'Subscription "ImportantEmails" must not select an introspection top level field.',
locations: [{ line: 3, column: 9 }],
},
]);
});

it('fails with introspection field in anonymous subscription', () => {
expectErrors(`
subscription {
__typename
}
`).to.deep.equal([
{
message:
'Anonymous Subscription must not select an introspection top level field.',
locations: [{ line: 3, column: 9 }],
},
]);
});
});
21 changes: 19 additions & 2 deletions src/validation/rules/SingleFieldSubscriptionsRule.js
Expand Up @@ -6,9 +6,10 @@ import type { OperationDefinitionNode } from '../../language/ast';
import type { ASTValidationContext } from '../ValidationContext';

/**
* Subscriptions must only include one field.
* Subscriptions must only include a non-introspection field.
*
* A GraphQL subscription is valid only if it contains a single root field.
* A GraphQL subscription is valid only if it contains a single root field and
* that root field is not an introspection field.
*/
export function SingleFieldSubscriptionsRule(
context: ASTValidationContext,
Expand All @@ -25,6 +26,22 @@ export function SingleFieldSubscriptionsRule(
node.selectionSet.selections.slice(1),
),
);
} else {
const selection = node.selectionSet.selections[0];
if (selection.kind === 'Field') {
const fieldName = selection.name.value;
// fieldName represents an introspection field if it starts with `__`
if (fieldName[0] === '_' && fieldName[1] === '_') {
context.reportError(
new GraphQLError(
node.name
? `Subscription "${node.name.value}" must not select an introspection top level field.`
: 'Anonymous Subscription must not select an introspection top level field.',
node.selectionSet.selections,
),
);
}
}
}
}
},
Expand Down

0 comments on commit afe10e7

Please sign in to comment.