Apollo-Server GraphQL Subscription on External WebSocket Server

Viewed 414

So I have a bit of a question since I'm having a hard time wrapping my head around it. Currently I have a GraphQL API Server created using Apollo-Server and persisted using a local sqlite database. I have the queries and mutations working correctly.

I also have an external WebSocket server that constantly has messages (that match my GraphQL/Database schema) produced to it at say ws://localhost:8000/websocket. Is it possible to have my GraphQL Server subscribe to that websocket address and constantly parse those messages and use the appropriate mutation to insert into the backend database?

I would then have a Vue frontend that would constantly display the results (via Vue Apollo Clients WS subscription maybe?)

2 Answers

to have my GraphQL Server subscribe to that websocket address and constantly parse those messages

Typically no, its the other way around - you can make ws server to call graphql server to do the mutations. That is if you want to use WS as the primary transport layer for everything - queries, mutations & subscriptions.

But usually architecture separates queries & mutations because they are more stateless and critical from subscriptions which are more stateful (persisted connection)

client -> queries & mutations -> graphql server --> redis pubsub -+
                                                                  |
client <--> subscriptions <-- graphql subscription server <-------+

(in simpler cases when you don't need high load, you can combine both servers to use in-memory pubsub)

BUT, if you very much want to, ofc you can write custom code to connect graphql server -> listen ws server in the background. See https://github.com/enisdenjo/graphql-ws#node-client for example The problem can appear if you have some user context. You would need to either have custom connection where changes of all users happen. Or have a dedicated connection for every user

Yes , it can be done quite easily , just write a service worker or a worker thread that constantly checks for new messages Can be done using worker_threads in node js

And if you need to implement it realtime Make sure your worker thread starts a socket connection and is constantly connected to the port where you are publishing your messages

You can do it using socket.io library

Related