同一端口上的 GraphQLServer + Socket-io

GraphQLServer + Socket-io on same port

我有一个工作项目,GraphQLServer 从端口 4000 为我的 React 应用程序提供服务,并在端口 5000 上侦听 socket-io。

我正在尝试部署到 heroku,所以我需要它们在同一端口上 (process.env.PORT),但我不知道如何用 GraphQLServer 做。

This is how to do it with express + socket-io

This is the start script for GraphQLServer

Gist with my current code is here

相关代码:

import server from './server';
import express from 'express';
import path from 'path';

const http = require('http').Server(server.express);
const io = require('socket.io')(http);
require('./socket')(io);

server.express.use(express.static(path.join(__dirname, '../../client/build')));
server.express.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '../../client/build', 'index.html'));
});

// Socket-io listener
http.listen({
    port: process.env.PORT || 5000
  }, () =>
  console.log('listening on port ' + process.env.PORT || 5000)
);

// GraphQL and app listener
server.start({
    cors: {
      credentials: true,
      origin: '/'
    }
    // port: process.env.PORT || 4000
  },
  () => {
    console.log('The server is up!');
  }
);

没有从 graphql-yoga, so asked on the prisma slack and was advised to use apollo-server-express 的开发者那里得到任何意见。

我注意到切换到 ApolloServer 的主要变化是:

  1. 它通过了 { req, res } 而不是 { request, response }
  2. 您需要使用 graphql-import 导入架构,例如:typeDefs: importSchema('./src/schema.graphql')

首先,我为 socket-io 创建了一个 express 应用程序和 httpServer,并告诉 io 监听使用 app:

实例化的 httpServer

const app = express();
const httpServer = require('http').createServer(app);
const io = require('socket.io')(httpServer);
require('./socket')(io); // my io.on('connection', socket => {}) function taking io as param
io.listen(httpServer);

然后我应用所有中间件并使用 app:

设置路由

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '../../client/build')));
  app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, '../../client/build', 'index.html'));
  });
} else {
  app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../../client/public', 'index.html'));
  });
}

app.use(cookieParser());

app.use((req, res, next) => {
  if (!req.cookies || !req.cookies.token) {
    return next();
  }
  const { token } = req.cookies;
  if (token) {
    console.log(process.env.PORT);
    const { userId } = jwt.verify(token, process.env.JWT_SECRET);
    // Put the userId onto the req for future requests to access
    req.userId = userId;
  }
  next();
});

最后(使用 ApolloServer 2)我将应用程序作为中间件应用到 ApolloServer 并告诉 httpServer 监听:

import server from './server' // my ApolloServer

server.applyMiddleware({
  app,
  path: '/graphql',
  cors: {
    credentials: true,
    origin: process.env.DOMAIN_FULL + ':' + process.env.PORT || '3000'
  }
});

httpServer.listen({
    port: process.env.PORT || 4000
  },
  () => console.log(`Server is running on ${server.graphqlPath}`)
);

确保客户端使用不带参数的 io() 进行实例化,并且您的 ApolloClient uri 是 '/graphql'