GraphQL 订阅返回空对象不会创建订阅

时间:2021-03-26 23:24:15

标签: javascript express graphql subscription

我正在尝试使用 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',
})

0 个答案:

没有答案