订阅入门

这是 GraphQL 库版本 6 的文档。对于长期支持 (LTS) 版本 5,请参阅 GraphQL 库版本 5 LTS

本指南介绍如何在 GraphQL 服务器上开始使用订阅功能。

如果您使用 Apollo Studio,请确保在连接设置中选择 graphql-ws 实现。

订阅可以侦听数据库的更改,包括与 GraphQL 库无关的更改。

启用订阅功能

Neo4j GraphQL 订阅依赖于 Neo4j 变更数据捕获。请确保按照 CDC 文档 中描述的步骤,以 FULL 模式为您的 Neo4j 实例启用它。

在 GraphQL 服务器上使用订阅之前,您必须通过将 subscriptions 功能传递给 Neo4jGraphQL 来启用它们。

new Neo4jGraphQL({
    typeDefs,
    driver,
    features: {
        subscriptions: true
    },
});

设置 @apollo/server 服务器

然后,下一步是安装以下依赖项

npm i --save ws graphql-ws neo4j-driver @neo4j/graphql express @apollo/server body-parser cors

将以下代码添加到您的 index.js 文件中以实现一个带有订阅的简单 @apollo/server 服务器(有关更多选项,请参阅 Apollo 的文档

import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import bodyParser from 'body-parser';
import cors from "cors";
import { createServer } from "http";
import neo4j from 'neo4j-driver';
import { Neo4jGraphQL } from '@neo4j/graphql';
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/lib/use/ws";
import express from 'express';

const typeDefs = `
    type Movie @node {
        title: String
    }

    type Actor @node {
        name: String
    }
`;

const driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("username", "password"));

const neoSchema = new Neo4jGraphQL({
    typeDefs,
    driver,
    features: {
        subscriptions: true
    },
});

async function main() {
    // Apollo server setup with WebSockets
    const app = express();
    const httpServer = createServer(app);
    const wsServer = new WebSocketServer({
        server: httpServer,
        path: "/graphql",
    });

    // Neo4j schema
    const schema = await neoSchema.getSchema();

    const serverCleanup = useServer(
        {
            schema,
            context: (ctx) => {
                return ctx;
            },
        },
        wsServer
    );

    const server = new ApolloServer({
        schema,
        plugins: [
            ApolloServerPluginDrainHttpServer({
                httpServer
            }),
            {
                async serverWillStart() {
                    return Promise.resolve({
                        async drainServer() {
                            await serverCleanup.dispose();
                        },
                    });
                },
            },
        ],
    });
    await server.start();

    app.use(
        "/graphql",
        cors(),
        bodyParser.json(),
        expressMiddleware(server, {
            context: async ({ req }) => ({ req }),
        })
    );

    const PORT = 4000;
    httpServer.listen(PORT, () => {
        console.log(`Server is now running on http://localhost:${PORT}/graphql`);
    });
}

main();

GraphQL 订阅

在先前的服务器运行后,可用的订阅将设置为 MovieActor。您可以使用以下语句订阅新创建的电影

subscription {
    movieCreated(where: { title_EQ: "The Matrix" }) {
        createdMovie {
            title
        }
    }
}

这样,任何使用匹配标题创建的新电影都将触发订阅。您可以使用以下查询尝试此操作

mutation {
    createMovies(input: [{ title_EQ: "The Matrix" }]) {
        movies {
            title
        }
    }
}