我将 Apollo-server
与 Nodejs
和 express
一起使用
和
subscriptions
创建实时连接Graphiql
查询或我的 Client
中运行订阅后遇到的问题:{
"error": "Could not connect to websocket endpoint ws://localhost:4000/subscription. Please check if the endpoint url is correct."
}
我使用的是 Mozilla Firefox
这是我的代码:
./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'))
./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 }
``