0

Please I need a help! I'm working on a nodejs backend server which I have apollo-server-express and socket.io working perfectly. I want to add subscription to my graphql but I cant get the both to work. If I use app.listen, the socket.io works while the subscription doesnt and if i use server.listen, the subscription works while the socket doesnt connect.

const express = require("express");
const socketIO = require("socket.io");
require("dotenv").config();
const http = require("http");
const {ApolloServer} = require("apollo-server-express");
const {ApolloServerPluginDrainHttpServer} = require("apollo-server- 
core");
const {makeExecutableSchema} = require("@graphql-tools/schema");
const typeDefs = require("./src/graphql/typeDefs");
const resolvers = require("./src/graphql/resolvers/index");
const {WebSocketServer} = require("ws");
const {useServer} = require("graphql-ws/lib/use/ws");

const PORT = process.env.PORT || 4000;

async function startServer() {
  const app = express();
  app.use(express.urlencoded({limit: "50mb", extended: true}));
  const schema = makeExecutableSchema({typeDefs, resolvers});
  const server = http.Server(app);
  const wsServer = new WebSocketServer({
    server,
    path: "/graphql",
  });
  const serverCleanup = useServer({schema}, wsServer);
  const apolloServer = new ApolloServer({
    schema,
    csrfPrevention: true,
    context: ({req}) => ({req}),
    plugins: [
    ApolloServerPluginDrainHttpServer({httpServer: server}),
    {
    async serverWillStart() {
      return {
        async drainServer() {
          await serverCleanup.dispose();
          },
        };
      },
    },
   ],
 });
await apolloServer.start();
apolloServer.applyMiddleware({app});
const socketServer = server.listen({port: PORT}, () => {
console.log(`Server running at 
   http://localhost:${PORT}${apolloServer.graphqlPath}`
  );
 });

const io = socketIO(socketServer);
Johndev247
  • 91
  • 6

0 Answers0