Skip to content

Commit 4fadf59

Browse files
committed
Add utils and validation modules to support subscriptions
1 parent 2a36773 commit 4fadf59

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

graphql_subscriptions/utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import re
2+
3+
4+
# From this response in Stackoverflow
5+
# http://stackoverflow.com/a/19053800/1072990
6+
def to_camel_case(snake_str):
7+
components = snake_str.split('_')
8+
# We capitalize the first letter of each component except the first one
9+
# with the 'title' method and join them together.
10+
return components[0] + "".join(x.title() if x else '_'
11+
for x in components[1:])
12+
13+
14+
# From this response in Stackoverflow
15+
# http://stackoverflow.com/a/1176023/1072990
16+
def to_snake_case(name):
17+
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
18+
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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

Comments
 (0)