javascript - GraphQL 订阅返回空对象不创建订阅
问题描述
我正在尝试使用 express-graphql 获得一个简单的 GraphQL 订阅模型。
当我使用时使用 Graphiql:
subscription {
newBook {
title
author
}
}
我得到:
{
"data": {
"newBook": null
}
}
它不创建订阅?我在这里做错了什么?
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema, execute, subscribe } = require('graphql');
// Pull in some specific Apollo packages:
const { PubSub } = require('graphql-subscriptions');
const { SubscriptionServer } = require('subscriptions-transport-ws');
// Create a server:
const app = express();
// Create a schema and a root resolver:
const schema = buildSchema(`
type Book {
title: String!
author: String!
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String!, author: String!): Book!
}
type Subscription {
newBook: Book
}
`)
const pubsub = new PubSub()
const books = [
{
title: "The Name of the Wind",
author: "Patrick Rothfuss",
},
{
title: "The Wise Man's Fear",
author: "Patrick Rothfuss",
}
]
const rootValue = {
books: () => {
return books
},
addBook: ({ title, author }) => {
const book = { title, author }
books.push(book)
pubsub.publish('NEW_BOOK', { newBook: book })
return book
},
Subscription: {
newBook: {
subscribe: () => pubsub.asyncIterator("NEW_BOOK")
}
}
}
app.use('/graphql', graphqlHTTP({
schema,
rootValue,
graphiql: true
}))
const server = app.listen(8080, () => console.log("Server started on port 8080"));
SubscriptionServer.create({ schema, rootValue, execute, subscribe }, {
server
})
pubsub.publish("NEW_BOOK", {
title: 'The Doors of Stone',
author: 'Patrick Rothfuss',
})
解决方案
推荐阅读
- reactjs - 输入后如何保持搜索状态?
- xamarin - Xamarin - 将 ActivityIndicator 可见性绑定到异步任务完成
- html - 为什么导航栏不在顶部?
- sql - 在 SQL 中是否有更简洁或更简单的方法来实现这一点?
- jquery - ma5menu 移动菜单未关闭
- macos - pycharm 快捷键被 mac 中的操作系统快捷键覆盖
- javascript - 如何将 DropzoneJS 与 PHP 和用户输入一起使用
- java - java中如何根据测试用例的值取n个输入?
- ios - 从 codemagic 编译颤振应用程序时出现 #error
- android - 我面临错误“未连接适配器;跳过布局”