Looking for code for a server side GraphQL subscription listener

独自空忆成欢 提交于 2019-12-20 04:54:18

问题


I have been looking high and low for some code that will allow me to register to a GraphQL subscription on the server side and read messages, coming from the external subscription server on the server side. I can get my server-side subscription client to connect to the external subscription server, but I after get an initial null message upon connection like so

{ message: 'From Default Listener',
  data: { data: { eventAdded: null } } }

no messages get captured there after. Help, please? Here is my code,

const ws = require('ws');
const { ApolloClient} = require('apollo-client');
const { SubscriptionClient } = require('subscriptions-transport-ws');
const { createHttpLink} = require( 'apollo-link-http');
const { InMemoryCache } = require('apollo-cache-inmemory');
const fetch = require('node-fetch');
const gql = require('graphql-tag');

const serverConfig = {
    serverUrl:'http://localhost:4000/', 
    subscriptionUrl:'ws://localhost:4000/graphql'
   };
const PORT = process.env.PORT || 4001;

let apollo;
let networkInterface;

const link = createHttpLink({ uri: serverConfig.serverUrl, fetch: fetch });

networkInterface = new SubscriptionClient(
    serverConfig.subscriptionUrl, { reconnect: true }, ws);
apollo = new ApolloClient({
    networkInterface ,
    link: link,
    cache: new InMemoryCache()
});

const client = () => apollo;
const subClient = client();
subClient.subscribe({
    query: gql`
        subscription eventAdded{
            eventAdded{
                id
                name
                payload
                createdAt
                storedAt
            }
        }
    `,
    variables: {}
}).subscribe({
    next: (data) => {
        console.log({message: 'From Default Listener', data});
    },
    error: (err)=>{
        console.log(err);
        done(err);
    }
});

If it turns out I've done something really dumb, please excuse me. Any help will be really appreciated.

PS: The subscription server is working fine when I subscribe and get messages using GraphQL Playground.


回答1:


Figured it out:

const ws = require('ws');
const { WebSocketLink } = require("apollo-link-ws");
const { execute} = require("apollo-link");
const { SubscriptionClient } = require('subscriptions-transport-ws');
const gql = require('graphql-tag');

const serverConfig = {serverUrl:'http://localhost:4000/', subscriptionUrl:'ws://localhost:4000/graphql'};

const client = new SubscriptionClient(serverConfig.subscriptionUrl, {
    reconnect: true
}, ws);

const link = new WebSocketLink(client);

const operation = {
    query: gql`
        subscription eventAdded{
            eventAdded{
                id
                name
                payload
                createdAt
                storedAt
            }
        }`
};

// execute returns an Observable so it can be subscribed to
execute(link, operation).subscribe({
    next: data => console.log(`received data: ${JSON.stringify(data, null, 2)}`),
    error: error => console.log(`received error ${error}`),
    complete: () => console.log(`complete`),
});

console.log(`Listener running at ${new Date().toString()}`);



回答2:


Similar implementation as above but in es2015:

var gql_ws = require('ws');  // needed because no native web socket implementation is present
var apollo_link = require("apollo-link");
var apollo_link_ws = require("apollo-link-ws");
var sub_trans_ws = require('subscriptions-transport-ws');

var gql = require('graphql-tag');

var gql_serverConfig = {
  serverUrl: 'https://endpoint',
  subscriptionUrl: 'ws://endpoint/graphql'
};

var gql_client = new sub_trans_ws.SubscriptionClient(gql_serverConfig.subscriptionUrl,{ reconnect: true }, gql_ws);
var gql_link = new apollo_link_ws.WebSocketLink(gql_client);

var query_object = `subscription {
  songUpdate {    
    current {
      time
      metadata{
        id
        artist
        title
      }
    }
  }
}`;

var gql_operation = { query: gql(query_object) };

// execute returns an Observable so it can be subscribed to
apollo_link.execute(gql_link, gql_operation).subscribe({
  next: function next(data) {
    return console.log("received data: " + JSON.stringify(data, null, 2));
  },
  error: function error(_error) {
    return console.log("received error " + _error);
  },
  complete: function complete() {
    return console.log("complete");
  }
});


来源:https://stackoverflow.com/questions/55233153/looking-for-code-for-a-server-side-graphql-subscription-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!