使用express-graphql,graphql,graphql-subscriptions和graphql-subscriptions-ws在GraphiQL上运行订阅

时间:2020-10-31 18:35:34

标签: graphql graphql-js express-graphql graphql-subscriptions

我是GraphQL的新手,目前通过在前端使用React编写测验应用程序来熟悉自己。

此刻,我在忙于后端。成功设置查询和变异后,我发现很难使订阅正常工作。使用Graph i QL时,我得到null作为输出,而不是“ 您的订阅数据将出现在这里...

查询和添加测验的变异。

Output of a subscription on GraphiQL

服务器的入口点 app.js

const express = require("express");
const mongoose = require("mongoose");
const { graphqlHTTP } = require("express-graphql");
const schema = require("./graphql/schema");
const cors = require("cors");

const port = 4000;

//Subscriptions 
const { createServer } = require("http");
const { SubscriptionServer } = require("subscriptions-transport-ws");
const { execute, subscribe } = require("graphql");

const subscriptionsEndpoint = `ws://localhost:${port}/subscriptions`;

const app = express();
app.use(cors());

mongoose.connect("mongodb://localhost/quizify", {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false
});

mongoose.connection.once("open", () => console.log("connected to database"));

app.use("/graphql", graphqlHTTP({
    schema,
    graphiql: true,
    subscriptionsEndpoint,
}));

const webServer = createServer(app);

webServer.listen(port, () => {
    console.log(`GraphQL is now running on http://localhost:${port}`);

    //Set up the WebSocket for handling GraphQL subscriptions. 
    new SubscriptionServer({
        execute,
        subscribe,
        schema
    }, {
        server: webServer,
        path: '/subscriptions',
    });
});

以下来自架构定义 schema.js

const { graphqlHTTP } = require("express-graphql");
const graphql = require("graphql");
const { PubSub } = require("graphql-subscriptions");

const pubsub = new PubSub();

//Import of Mongoose Schemas: 
const Quiz = require("../models/quiz");

const {
    GraphQLObjectType,
    GraphQLList,
    GraphQLSchema,
    GraphQLNonNull,
    GraphQLID,
    GraphQLString,
    GraphQLBoolean
} = graphql;

const QuizType = new GraphQLObjectType({
    name: "Quiz",
    fields: () => ({
        id: { type: GraphQLID },
        title: { type: GraphQLString },
        questions: {
            type: new GraphQLList(QuestionType),
            resolve(parent, args) {
                return Question.find({ quizId: parent.id });
            }
        },
        creator: {
            type: UserType,
            resolve(parent, args) {
                return User.findById(parent.creatorId);
            }
        }
    })
});

const NEW_QUIZ_ADDED = "new_quiz_added";

const Subscription = new GraphQLObjectType({
    name: "Subscription",
    fields: {
        quizAdded: {
            type: QuizType,
            subscribe: () => {
                pubsub.asyncIterator(NEW_QUIZ_ADDED);
            },
        },
    }
});

const Mutation = new GraphQLObjectType({
    name: "Mutation",
    fields: {
        createQuiz: {
            type: QuizType,
            args: {
                title: { type: new GraphQLNonNull(GraphQLString) },
                creatorId: { type: new GraphQLNonNull(GraphQLID) }
            },
            resolve(parent, args) {
                const newQuiz = new Quiz({ //Quiz imported from Mongoose schema. 
                    title: args.title,
                    creatorId: args.creatorId,
                });
                pubsub.publish(NEW_QUIZ_ADDED, { quizAdded }); //NEW_QUIZ_ADDED - a constant defined above for easier referencing. 
                return newQuiz.save();
            }
        },
    },
});

module.exports = new GraphQLSchema({
    query: RootQuery,
    mutation: Mutation,
    subscription: Subscription,
}); 

我环顾四周,但是找不到适用于此类网站的方法。我知道这听起来像是一个简单的问题。任何帮助将不胜感激!

0 个答案:

没有答案