温馨提示:本文翻译自stackoverflow.com,查看原文请点击:express - Apollo Server as Nuxt serverMiddleware
apollo express nuxt.js websocket subscription

express - Apollo Server作为Nuxt服务器

发布于 2020-03-28 23:26:13

我设法在Nuxtjs中将express + Apollo Backend作为serverMiddleware。一切正常(身份验证,缓存,数据源,查询,变异),但是现在我正在尝试使订阅(websockets)运行,这给我带来了麻烦。

我尝试了这个示例https://www.apollographql.com/docs/apollo-server/data/subscriptions/#subscriptions-with-additional-middleware,但即使让httpServer侦听也不起作用。

这是我的API文件,我需要通过nuxt.config.js使用'~/api/index'

module.exports = async () => {
  const app = require('express')()
  const server = await require("./apollo")() // apollo-server-express w/ typeDefs and resolvers

  // apply Apollo to Express
  server.applyMiddleware({ app });
  console.log(`???? ApolloServer ready at ${server.graphqlPath}`);

  const httpServer = http.createServer(app);
  server.installSubscriptionHandlers(httpServer);
  console.log(`???? ApolloSubscriptions ready at ${server.subscriptionsPath}`);

  return {
    path: '/api',
    handler: httpServer
  }
}

现在我的操场给我这个错误: "Could not connect to websocket endpoint ws://192.168.150.98:3000/api/graphql. Please check if the endpoint url is correct."

TypeDefs:

type Subscription {
  postAdded: Post
}
type Post {
  author: String
  comment: String
}
type Query {
  posts: [Post]
}
type Mutation {
  addPost(author: String, comment: String): Post
}

解析器:

Query: {
  posts(root, args, context) {
    return Posts;
  }
}
Mutation: {
  addPost(root, args, context) {
    pubsub.publish(POST_ADDED, { postAdded: args });
    return Posts.add(args);
  }
},
Subscription: {
  postAdded: {
    // Additional event labels can be passed to asyncIterator creation
    subscribe: () => pubsub.asyncIterator([POST_ADDED]),
  },
}

这里的第一个问题,谢谢你!:)

查看更多

查看更多

提问者
jliehmann
被浏览
166
jliehmann 2020-01-31 17:36

我发现了一种简便的方法来实现,将代码作为nuxt模块导入:

import http from 'http'

export default function () {
  this.nuxt.hook('render:before', async () => {
    const server = require("./apollo")()

    // apply Apollo to Express
    server.applyMiddleware({ app: this.nuxt.renderer.app });
    console.log(`???? ApolloServer ready at ${server.graphqlPath}`);

    const httpServer = http.createServer(this.nuxt.renderer.app);

    // apply SubscriptionHandlers to httpServer
    server.installSubscriptionHandlers(httpServer);
    console.log(`???? ApolloSubscriptions ready at ${server.subscriptionsPath}`);

    // overwrite nuxt.server.listen()
    this.nuxt.server.listen = (port, host) => new Promise(resolve => httpServer.listen(port || 3000, host || 'localhost', resolve))

    // close this httpServer on 'close' event
    this.nuxt.hook('close', () => new Promise(httpServer.close))
  })
}

我现在正在使用一种可能更稳定的方法,以编程方式使用nuxt用hapi代替express,因为express给我带来了麻烦,并且没有显示加载屏幕(建筑进度)。只需使用npx create-nuxt-app并创建带有hapi服务器后端的应用即可。

具有hapi的代码如下所示:

const consola = require('consola')
const Hapi = require('@hapi/hapi')
const HapiNuxt = require('@nuxtjs/hapi')

async function start () {
  const server = require('./apollo/index')()
  const app = new Hapi.Server({
    host: process.env.HOST || '127.0.0.1',
    port: process.env.PORT || 3000
  })

  await app.register({
    plugin: HapiNuxt
  })

  app.route(await require('./routes')())

  await server.applyMiddleware({
    app,
    path: '/graphql'
  });
  console.log(`???? ApolloServer ready at ${server.graphqlPath}`);
  await server.installSubscriptionHandlers(app.listener)
  console.log(`???? ApolloSubscriptions ready at ${server.subscriptionsPath}`);

  await app.start()

  consola.ready({
    message: `Server running at: ${app.info.uri}`,
    badge: true
  })
}
process.on('unhandledRejection', error => consola.error(error))
start().catch(error => console.log(error))

也许我可以帮助别人