Apollo Server - подключение веб-сокета к GraphQL не сохраняется - PullRequest
0 голосов
/ 27 марта 2020

Я работал с подписками graphql и смог реализовать это. Он работает нормально без каких-либо проблем, когда я размещаю то же самое на локальном компьютере. Но когда я развертываю его на сервере с idle_timeout, установленным в «x» секунд, он разрывает соединение с клиентом на площадке Graphql через эти «x» секунды. Я ожидаю, что это сохранится ...

Вот мой код

const http = require('http');
const {ApolloServer, gql} = require('apollo-server-express');
const express = require('express');
const db = require('./db');
const { PubSub, withFilter } = require('graphql-subscriptions')
const env = require('./config');
const cors = require('cors');


const pubSub = new PubSub();
const app = express();
app.use(cors());

const typeDefs = gql`
    type Query {
        qflEventTypes: [String]
    }

    type Mutation {
        pushQflData(symbol: String, date: Int, field: String, value: String, type: String) : Boolean
        pushQflDBEvent(event : String, date : Int, factor : String) : Boolean
    }

    type Subscription {
        qflDataChange: qflData
        qflEventChange(eventname : String): qflEvent
    }

    type qflData {
        symbol : String
        date : Int
        field : String
        value : String
        type : String
    }

    type qflEvent {
        event : String
        date : Int
        factor : String
    }
`;

const resolvers = {
    Query: {
        qflEventTypes(){
            return db.qflevents.list().map(a => a.eventname);
        }
    },
    Mutation: {
        pushQflData : (root,{symbol,date,field,value,type}) => {
            pubSub.publish('QFL_DATA_CHANGED', {qflDataChange: {symbol,date,field,value,type}}) 
            return true;
        },
        pushQflDBEvent : (root,{event,date,factor}) => {
            pubSub.publish('QFL_EVENT_CHANGED', {qflEventChange: {event,date,factor}}) 
            return true;
        }
    },
    Subscription: {
        qflDataChange :{
            subscribe: () => pubSub.asyncIterator('QFL_DATA_CHANGED')
        },
        qflEventChange : {
            subscribe: withFilter(() => pubSub.asyncIterator('QFL_EVENT_CHANGED'), (payload, variables) => {
                return payload.qflEventChange.event === variables.eventname;
        })
        }
    }
};


const server = new ApolloServer({
    typeDefs,
    resolvers,
    introspection: true, // enables introspection of the schema
    playground: true, // enables the actual playground
    subscriptions: {
      path: '/api/ws',
      keepAlive: 15000,
      onConnect: () => console.log("connected"),
      onDisconnect: () => console.log("disconnected")
    }
});

server.applyMiddleware({app,path: '/api/ql', cors: false});

const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

var port = env.Runtime.PORT || 9000

httpServer.listen(port, () => {
    console.log(`? Server ready at http://localhost:${port}${server.graphqlPath}`)
    console.log(`? Subscriptions ready at ws://localhost:${port}${server.subscriptionsPath}`)
  })


Я уже потратил пару дней на то же самое. Если кто-то может помочь мне или дать мне руководство, это будет полезно.

...