|
| 1 | +from graphql import GraphQLError |
| 2 | +from graphql.validation.rules.base import ValidationRule |
| 3 | + |
| 4 | +FIELD = 'Field' |
| 5 | + |
| 6 | +# XXX from Apollo pacakge: Temporarily use this validation |
| 7 | +# rule to make our life a bit easier. |
| 8 | + |
| 9 | + |
| 10 | +class SubscriptionHasSingleRootField(ValidationRule): |
| 11 | + __slots__ = 'field', |
| 12 | + |
| 13 | + def __init__(self, context): |
| 14 | + self.field = FIELD |
| 15 | + super(SubscriptionHasSingleRootField, self).__init__(context) |
| 16 | + |
| 17 | + def enter_OperationDefinition(self, node, key, parent, path, ancestors): |
| 18 | + schema = self.context.get_schema() |
| 19 | + schema.get_subscription_type() |
| 20 | + operation_name = node.name.value if node.name else '' |
| 21 | + num_fields = 0 |
| 22 | + for selection in node.selection_set.selections: |
| 23 | + # TODO: Fix this string assertion of "Field"...Apollo did this |
| 24 | + # in their package and since I was porting, just followed the same |
| 25 | + if type(selection).__name__ == self.field: |
| 26 | + num_fields += 1 |
| 27 | + else: |
| 28 | + self.context.report_error( |
| 29 | + GraphQLError( |
| 30 | + 'Apollo subscriptions do not support fragments on\ |
| 31 | + the root field', [node])) |
| 32 | + if num_fields > 1: |
| 33 | + self.context.report_error( |
| 34 | + GraphQLError( |
| 35 | + self.too_many_subscription_fields_error(operation_name), |
| 36 | + [node])) |
| 37 | + return False |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def too_many_subscription_fields_error(subscription_name): |
| 41 | + return 'Subscription "{0}" must have only one\ |
| 42 | + field.'.format(subscription_name) |
0 commit comments