Apollo-server: websockets for query & mutations

Created on 24 Oct 2017  路  8Comments  路  Source: apollographql/apollo-server

Hi guys,

I've one idea, I want to use websockets not only for subscriptions, but also for query and mutations too. Is it possible with current apollo-server?

I think it would not be difficult to be implemented, I was not able to find any documentation about that, if you have any kind of information or ideas please share it with me.

P.S. I think it will be the next level for modern web. http post is a legacy that should be dropped away imho.

Most helpful comment

You'll be happy to hear the existing subscriptions-transport-ws already supports this!

All 8 comments

You'll be happy to hear the existing subscriptions-transport-ws already supports this!

It looks like I was searching answers in wrong repository :) thanks @martijnwalraven !

You can do this easily. I am using SocketCluster with makeExecutableSchema and graphql's execute. SocketCluster is great because it handles web token authentication for you and gives you scalability out of the box. Have a look at this repo for a good reference implementation.

Very interesting, thanks @Panoplos I'll take a look 馃憤

Yes, subscriptions-transport-ws supports this feature. But I noticed that apollo-server-express graphiql is failed to use full websocket.

I did something like this

const id = Math.random();

const req = link.request({
    query: gql`mutation {
        publisherMutation(message: "${id}")
    }`
});
if (req) {
    const sub = req.subscribe(res => {
        console.log("publisherMutation:", res);
        sub.unsubscribe()
    });
}`

And here's my full code

import {WebSocketLink} from "apollo-link-ws";
import {SubscriptionClient} from "subscriptions-transport-ws";
import gql from "graphql-tag";

const GRAPHQL_ENDPOINT = "ws://localhost:3000/graphql";


const client = new SubscriptionClient(GRAPHQL_ENDPOINT, {
    reconnect: true
});

const link = new WebSocketLink(client);

const id = Math.random();

const req = link.request({
    query: gql`mutation {
        publisherMutation(message: "${id}")
    }`
});
if (req) {
    const sub = req.subscribe(res => {
        console.log("publisherMutation:", res);
        sub.unsubscribe()
    });
}

remember my code is to mutate and is not subscription but it did not have any choice to call mutate without it.
if anyone has a better way to do this I would be glad with many thanks :)

Was this page helpful?
0 / 5 - 0 ratings