I'm trying to get websockets working with a graphq...
# ktor
d
I'm trying to get websockets working with a graphql backend (http://graphql-java.readthedocs.io/en/latest/subscriptions.html). How do I have to configure ktor to achieve this? Thanks for any help
d
If the websocket protocol is not explained, but only explained a higher level API. I guess your best bet is to either check the source-code, or use Chrome developer tools to check the WebSocket frames sent/received
Once you have some samples, if it is JSON for example, you can serialize frames using Gson
d
so I guess that this is what I need to map to ktor, correct?
what's the correct place to do this?
d
What do you want is to use the library directly? Or to reimplement it using ktor?
d
I'd like to use the graphql functionality of this library to process requests coming in via ktor server.
for regular requests, i.e. not subscriptions/websockets, the integration looks something along this:``` val handler = GraphQLHandler(schema, resolvers) val server = embeddedServer(Netty, port = 8888) { install(ContentNegotiation) { jackson { } } routing { post("/graphql") { val request = call.receive<Request>() val result = handler.execute(request.query, ...) call.respond(mapOf("data" to result.getData<Any>())) } } } ```
d
Ok. So you simply want to use the library and somehow consume its results inside a route
You want to reverse proxy the websocket or something? Consume the results and publish to a websocket route of your ktor backend?
d
yes I guess that's correct (I'm not very familiar with websockets yet 😉 )
d
Ok. It seems that that API returns a
Publisher
and a
Subscription
, and you can provide a object that will receive results in the
onNext
, method. The idea is to call to se
websocketSession.outgoing.send
to send a frame with the content
if you need to subscribe once, and then serve to several clientes, you will have to use a channel to produce results and read for each client
d
how would the websocketSession and the Publisher be connected?
well I guess that I have to read my way through https://ktor.io/samples/websockets.html again with the information that you've given me. Thanks
d
If you have a
websocketSession
instance, it has a
outgoing
property with a send method
you can call it inside the
onNext
method
that would be the easiest way of doing it, you could also try to convert the Subscription or something into a ktor channel, map and try to pipe it, but that would be more complex
you can for example like a chat, store all the websocketSession instances that need to be notified inside a Set, and then when receiving in the
onNext
method, a message, iterate over all the websocketSession instances, and call
session.outgoing.send(Frame(…))
to notify all the clients
but I guess that the first step is to try it by yourself to get familiarized about stuff
d
yes, I guess that's the case