All files validation.ts

100% Statements 15/15
100% Branches 4/4
100% Functions 4/4
100% Lines 15/15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 381x             1x       2x           14x 14x 14x   15x 15x 15x 17x 15x     2x     15x 2x   15x      
import {
  ValidationContext,
  Selection,
  GraphQLError,
} from 'graphql';
 
// XXX I don't know how else to do this. Can't seem to import from GraphQL.
const FIELD = 'Field';
 
 
export function tooManySubscriptionFieldsError(subscriptionName: string): string {
  return `Subscription "${subscriptionName}" must have only one field.`;
}
 
// XXX we temporarily use this validation rule to make our life a bit easier.
 
export function subscriptionHasSingleRootField(context: ValidationContext): any {
  const schema = context.getSchema();
  schema.getSubscriptionType();
  return {
    OperationDefinition(node) {
      const operationName = node.name.value;
      let numFields = 0;
      node.selectionSet.selections.forEach( (selection: Selection) => {
        if (selection.kind === FIELD) {
          numFields++;
        } else {
          // why the heck use a fragment on the Subscription type? Just ... don't
          context.reportError(new GraphQLError('Apollo subscriptions do not support fragments on the root field', node));
        }
      });
      if (numFields > 1) {
        context.reportError(new GraphQLError(tooManySubscriptionFieldsError(operationName), node));
      }
      return false;
    },
  };
}