Looking for code for a server side GraphQL subscription listener

前端 未结 2 1744
耶瑟儿~
耶瑟儿~ 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:42

    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()}`);
    

提交回复
热议问题