Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to establish connection for socket io and graphql?

I am very new to graphql... here is my server file... I not being able to establish the socket io connection ... when I do console inside socket io it does not go inside the function... I think I am doing something wrong here const io = require('socket.io')(server)...

var express = require('express');
var graphqlHTTP = require('express-graphql');
var {schema} = require('../graphql/schema');
var {root} = require('../graphql/resolver');

const EventEmitter = require('events');
var app = express();
var server = require('http').Server(app);
const event = new EventEmitter()
const io = require('socket.io')(server)
event.on('event', function(action) {
  console.log(action)
  io.on('connection', function (socket) {
    console.log('socket')
    socket.emit('action', action)
  })
})

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
  formatError(err) {
    return {
      message: err.message
    };
  }
}));
app.use('/voyager', middleware({ endpointUrl: '/graphql' }));
app.listen(3019);
like image 655
Dark Knight Avatar asked Mar 12 '18 10:03

Dark Knight


People also ask

Can I use Socket.IO with GraphQL?

The @n1ru4l/socket-io-graphql-client package can be used to execute (live) Query , Mutation and Subscription operations on to the server setup by @n1ru4l/socket-io-graphql-server . It implements the underlying GraphQL over Socket.io protocol.

How does Socket.IO connection work?

Socket.IO allows bi-directional communication between client and server. Bi-directional communications are enabled when a client has Socket.IO in the browser, and a server has also integrated the Socket.IO package. While data can be sent in a number of forms, JSON is the simplest.

Does Apollo client use WebSockets?

Instead, Apollo Client subscriptions most commonly communicate over WebSocket, via the graphql-ws library. As mentioned in Choosing a subscription protocol, some servers use an older library called subscriptions-transport-ws .


1 Answers

apollo server - "... is the best way to quickly build a production-ready, self-documenting API for GraphQL clients, using data from any source."

apollo-server-express - use apollo as a 'middleware' to your app variable

// Node modules imports
require('dotenv').config({ path: './variables.env' })
const express = require('express')
const socketio = require('socket.io')
const { ApolloServer, gql } = require('apollo-server-express')

// Initalizes the app server
const app = express()

const typeDefs = gql`
  type Query {
    foo: String
  }
`;

const resolvers = {
  Query: {
    foo: () => 'Foo world!'
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });


// Listen to port 5000, save on const to attach io to it
const http = app.listen(5000, () =>
  console.log("🚀 Server ready at http://localhost:5000" + server.graphqlPath)
)

// Attach socket.io to the server instance
const io = socketio(http)
io.on('connection', (socket) => {
   // related io code
})

I deeply recommend you to read the docs from apollo

Updated for @Coder

Remember to always wrap all your io code inside the connection method from io.
Btw you are creating two server instances, one Express and one Http.
Store the server from express into a const and use it for the socket.io.

const app = express()
const server = app.listen(3019)

const io = require('socket.io')(server)
io.on('connection', (socket) => {
    console.log('connected to socket')
    // do event here inside
    // enter code here
    socket.on('some_event',()=>{ // do something })
    socket.on('some_event_2',()=>{ // do something 2 })
    socket.on('some_event_3',()=>{ // do something 3 })
})
like image 60
William Avatar answered Sep 21 '22 13:09

William