This repository has been archived by the owner on May 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
routing.py
98 lines (73 loc) · 2.46 KB
/
routing.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
import asyncio
from ariadne import gql, ResolverMap
from ariadne.executable_schema import make_executable_schema
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from graphql.pyutils import EventEmitter, EventEmitterAsyncIterator
from graphql.subscription import subscribe
from .database import db, init_database, Note
from .graphql import GraphQLHTTPConsumer, GraphQLWebsocketConsumer
from .subscription import SubscriptionAwareResolverMap
SCHEMA = gql(
"""
type Note {
id: ID!
title: String
body: String
}
type Query {
hello: String!
notes: [Note!]!
notesContaining(query: String!): [Note!]!
}
type Mutation {
createNote(title: String!, body: String!): Note!
sendMessage(message: String!): Boolean!
}
type Subscription {
messages: String!
}
"""
)
mutation = ResolverMap("Mutation")
pubsub = EventEmitter()
query = ResolverMap("Query")
subscription = SubscriptionAwareResolverMap("Subscription")
@query.field("hello")
async def say_hello(root, info):
await asyncio.sleep(3)
return "Hello!"
@query.field("notes")
async def get_all_notes(root, info):
await init_database() # FIXME: channels needs to expose the ready_callable from daphne
notes = await Note.query.gino.all()
return notes
@query.field("notesContaining")
async def get_notes_containing(root, info, query: str):
await init_database() # FIXME: channels needs to expose the ready_callable from daphne
notes = await Note.query.where(Note.title.like("%{}%".format(query))).gino.all()
return notes
@mutation.field("sendMessage")
async def send_message(root, info, message):
pubsub.emit("message", message)
return True
@mutation.field("createNote")
async def create_note(root, info, title: str, body: str):
await init_database() # FIXME: channels needs to expose the ready_callable from daphne
note = await Note.create(title=title, body=body)
return note
@subscription.subscription("messages")
def subscribe_messages(root, info):
return EventEmitterAsyncIterator(pubsub, "message")
@subscription.field("messages")
def push_message(message, info):
return message
schema = make_executable_schema(SCHEMA, [mutation, query, subscription])
application = ProtocolTypeRouter(
{
"http": URLRouter([url(r"^graphql/$", GraphQLHTTPConsumer.for_schema(schema))]),
"websocket": URLRouter(
[url(r"^graphql/$", GraphQLWebsocketConsumer.for_schema(schema))]
),
}
)