订阅 Apollo 服务器不工作 - Nodejs/Express

时间:2021-03-16 10:51:00

标签: node.js express apollo apollo-server

我将 Apollo-serverNodejsexpress 一起使用 和

  1. 添加一本新书
  2. 我正在尝试使用 subscriptions 创建实时连接
  3. 但是我在 Graphiql 查询或我的 Client 中运行订阅后遇到的问题:
{
  "error": "Could not connect to websocket endpoint ws://localhost:4000/subscription. Please check if the endpoint url is correct."
}
  1. 我使用的是 Mozilla Firefox

  2. 这是我的代码:

./index.js

const { ApolloServer, gql } = require('apollo-server-express')
const { resolvers, typeDefs } = require('./schema')
const { PubSub } = require('apollo-server')
const express = require('express')
const cors = require('cors')

const pubsub = new PubSub()
const app = express()
app.use(cors())

const server = new ApolloServer({
    resolvers, typeDefs, context: () => ({ pubsub })
})

server.applyMiddleware({ app, cors: true })

app.listen(4000, (res) => console.log('connected : http://localhost:4000/graphql'))

  1. 这是我的架构文件:

./schema.js

const { gql } = require('apollo-server')

// my DB
const books = [
    { id: 1, title: 'the 7 habits', authorId: 1 },
    { id: 2, title: 'the 9 Ahmed Googe', authorId: 2 },
    { id: 3, title: 'How To use Google', authorId: 1 },
    { id: 4, title: 'Go ahead', authorId: 1 },
    { id: 5, title: 'Dont be stuped', authorId: 3 },
    { id: 6, title: 'OMG', authorId: 2 },
    { id: 7, title: 'Dont work for monty but work for life', authorId: 2 },
]

const typeDefs = gql`
    type Query{
        books: [BookType]
    }
    type BookType {
        title: String
    }
    type Mutation{
        addBook(title: String): BookType
    }
    #Subscription 
    type Subscription{
        addBookSub:BookType
    }
`

const resolvers = {
    Query: {
        books: () => books,
    },
    Mutation: {
        addBook: (_, args, { pubsub }) => {
            const newBook = { title: args.title }
            pubsub.publish('BOOK_ADDED', { addBookSub: newBook })
            books.push(newBook)
            return newBook
        }
    },
    Subscription: {
        addBookSub: {
            subscirbe: (_, __, { pubsub }) => pubsub.asyncIterator("BOOK_ADDED")
        }
    }
}

module.exports = { resolvers, typeDefs }
``

0 个答案:

没有答案