-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.py
129 lines (99 loc) · 2.87 KB
/
schema.py
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import graphene
import json
import uuid
from datetime import datetime
class Post(graphene.ObjectType):
title = graphene.String()
content = graphene.String()
class User(graphene.ObjectType):
id = graphene.ID(default_value=str(uuid.uuid4()))
username = graphene.String()
created_at = graphene.DateTime(default_value=datetime.now())
avatar_url = graphene.String()
def resolve_avatar_url(self, info):
return 'https://cloudinary.com/{}/{}'.format(self.username, self.id)
class Query(graphene.ObjectType):
hello = graphene.String()
is_admin = graphene.Boolean()
users = graphene.List(User, limit=graphene.Int())
def resolve_hello(self, info):
return "world"
def resolve_is_admin(self, info):
return True
def resolve_users(self, info, limit=None):
# default values make the arguement optional
return [
User(id="1", username="Fred", created_at=datetime.now()),
User(id="2", username="Mary", created_at=datetime.now()),
User(id="3", username="Jim", created_at=datetime.now()),
][:limit]
class CreateUser(graphene.Mutation):
user = graphene.Field(User)
class Arguments:
username = graphene.String()
def mutate(self, info, username):
user = User(username=username)
return CreateUser(user=user)
class CreatePost(graphene.Mutation):
post = graphene.Field(Post)
class Arguments:
title = graphene.String()
content = graphene.String()
def mutate(self, info, title, content):
is_anonymous = info.context.get('is_anonymous')
if is_anonymous:
raise Exception('Not Authenticated')
post = Post(title=title, content=content)
return CreatePost(post=post)
class Mutation(graphene.ObjectType):
create_user = CreateUser.Field()
create_post = CreatePost.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
result = schema.execute(
'''
query getUsersQuery ($limit: Int) {
hello
isAdmin
users(limit: $limit) {
id
username
createdAt
avatarUrl
}
}
''',
variable_values={'limit': 1}
)
dictResult = dict(result.data.items())
print(json.dumps(dictResult, indent=2))
result = schema.execute(
'''
mutation($username: String) {
createUser(username: $username) {
user {
id
username
}
}
}
''',
variable_values={'username': 'Freddo Bar'}
)
result = schema.execute(
'''
mutation {
createPost(title: "Hello", content: "World") {
post {
title
content
}
}
}
''',
context={
'is_anonymous': False
}
)
# print(result)
dictResult = dict(result.data.items())
print(json.dumps(dictResult, indent=2))