socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

Wont work on GraphQL Yoga

Open allestaire opened this issue 3 years ago • 4 comments

Description

  • Seems like this wont work on GraphQL Yoga, but upon setting it up there are no errors
  • Already tried putting the Socket.io config after server.start but no luck
const express = require('express');
const { GraphQLServer, PubSub } = require('graphql-yoga');
...
const graphQLServer = new GraphQLServer({
  typeDefs: TYPE_DEFS,
  resolvers,
  middlewares: [yupMiddleware()],
  context: request => {
    return {
      ...request,
      prisma,
      pubsub,
    }
  },
})
server.express.use('/uploads', express.static('uploads'))
...
const io = socketio(graphQLServer)
io.on('connection', async (socket) => {
  console.log('a user connected');
});

allestaire avatar Oct 18 '22 06:10 allestaire

Hi! It seems you can pass a raw HTTP server: https://www.the-guild.dev/graphql/yoga-server/v3

import { createServer } from 'node:http'
import { createYoga } from 'graphql-yoga'
import { schema } from './schema'

// Create a Yoga instance with a GraphQL schema.
const yoga = createYoga({ schema })

// Pass it into a server to hook into request handlers.
const server = createServer(yoga)

// Start the server and you're done!
server.listen(4000, () => {
 console.info('Server is running on http://localhost:4000/graphql')
})

So you should be able to reuse the same server with Socket.IO.

darrachequesne avatar Oct 18 '22 07:10 darrachequesne

Thanks for the quick response @darrachequesne , but on this project (sorry did not include on the code) I was using express, is that possible?

allestaire avatar Oct 18 '22 07:10 allestaire

You should be able to do what you want with Express as well:

import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { /* options */ });

io.on("connection", (socket) => {
  // ...
});

httpServer.listen(3000);

Reference: https://socket.io/docs/v4/server-initialization/#with-express

darrachequesne avatar Oct 18 '22 07:10 darrachequesne

The problem is, express is wrapped with GrapQL Yoga, is that still possible?

allestaire avatar Oct 18 '22 08:10 allestaire