Looking for code for a server side GraphQL subscription listener

前端 未结 2 1738
耶瑟儿~
耶瑟儿~ 2021-01-25 00:15

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 subscripti

2条回答
  •  北海茫月
    2021-01-25 00:39

    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");
      }
    });
    

提交回复
热议问题