Learn GraphQL · 10/15

Real-Time Data with Subscriptions

2 min read

实时数据与订阅

欢迎来到 GraphQL 课程的下一部分! 👨‍🏫 在本指南中,我们将深入探讨 GraphQL 订阅的激动人心的世界,这是一种在您的应用程序中实现实时数据的强大功能。

1. 了解订阅和 WebSocket 🕵️‍♂️

问题: 想象一下您正在构建一个实时聊天应用程序。当新消息到达时,您希望它立即显示给所有用户。使用传统的请求-响应模型(如查询),客户端必须不断向服务器询问新数据(轮询)。这效率低下,会给服务器带来不必要的负载,并且更新不是即时的。

解决方案: 进入 GraphQL 订阅!订阅是一种 GraphQL 操作,允许服务器在特定事件发生时将数据推送到客户端。 这对于需要实时更新的应用程序(例如聊天应用程序、实时通知和体育比分更新)非常有用。

那么,WebSocket 是如何融入其中的呢? 🤔

虽然 GraphQL 规范没有为订阅定义特定的传输协议,但它们通常是通过 WebSocket 实现的。 WebSocket 在客户端和服务器之间提供了一个持久的双向通信通道。 这意味着服务器可以在数据可用时立即将其推送给客户端,而无需客户端发起请求。把它想象成一条专用的电话线,而不是不断地拨打电话来查看是否有任何新消息。

有趣的事实: 虽然 WebSocket 是最常见的选择,但也可以使用其他技术,例如服务器发送事件 (SSE)。

2. 设置 PubSub:发出事件 📡

问题: 好的,所以我们知道我们需要将更新从服务器推送到客户端。但是服务器如何知道何时发生了值得推送的事件,以及将更新推送到哪里?

解决方案: 输入发布/订阅(PubSub)模型。 这是一个消息传递模式,其中消息的发送者(发布者)不会将消息直接发送给特定的接收者(订阅者)。 相反,发布者将消息发送到一个名为“主题”或“频道”的中间人,订阅者可以表示对接收来自特定主题的消息感兴趣。

在 GraphQL 订阅的上下文中:

  • 发布者 通常是一个突变解析器。当突变更改数据时,它会将事件发布到特定的主题。
  • 订阅者 是通过订阅操作连接到服务器的客户端。
  • PubSub 系统 充当事件的中心枢纽。

对于简单的应用程序或开发环境,可以使用内存中的 PubSub 实现,例如 graphql-subscriptions 包提供的 PubSub 类。 对于更具可扩展性的生产环境,建议使用基于 Redis 或 Kafka 等外部消息代理的 PubSub 系统。

入门:

要开始使用,您需要安装必要的包。对于一个基本的设置,您通常会使用 graphql-ws 和 ws。

bash
npm install graphql-ws ws

接下来,您需要在服务器中创建一个 PubSub 实例。

javascript
import { PubSub } from 'graphql-subscriptions';

export const pubsub = new PubSub();

这个 pubsub 实例将用于在您的解析器中发布和订阅事件。

3. 从突变中触发订阅 💥

问题: 现在我们有了 PubSub 系统,我们如何将突变(数据更改)连接到订阅(实时更新)?

解决方案: 魔法发生在您的突变解析器中!在突变成功更新数据后,您将使用 pubsub.publish() 方法向特定主题发出事件。

让我们来看一个例子。假设我们有一个 createMessage 突变:

架构定义 (SDL):

首先,在您的 GraphQL 架构中定义您的 Subscription 类型。

graphql
type Subscription {
  newMessage: Message!
}

type Mutation {
  createMessage(text: String!): Message!
}

type Message {
  id: ID!
  text: String!
}

解析器:

在您的解析器文件中,您将实现 createMessage 突变和 newMessage 订阅。

javascript
import { pubsub } from './pubsub'; // 从您创建它的文件中导入

const resolvers = {
  Subscription: {
    newMessage: {
      subscribe: () => pubsub.asyncIterator(['NEW_MESSAGE'])
    }
  },
  Mutation: {
    createMessage: (parent, { text }) => {
      const message = { id: Date.now().toString(), text };
      // 将事件发布到“NEW_MESSAGE”主题
      pubsub.publish('NEW_MESSAGE', { newMessage: message });
      return message;
    }
  }
};

分解:

  • newMessage.subscribe: 此函数告诉 GraphQL 引擎,任何订阅 newMessage 的客户端都应该收听 NEW_MESSAGE 主题上的事件。 pubsub.asyncIterator() 返回一个 AsyncIterator,GraphQL 服务器使用它将事件数据推送到客户端。
  • pubsub.publish('NEW_MESSAGE', { newMessage: message }): 在创建新消息后,我们立即将一个事件发布到 NEW_MESSAGE 主题。发布的有效负载(第二个参数)的形状应与订阅字段返回的类型相匹配。

现在,每当执行 createMessage 突变时,所有订阅了 newMessage 的连接客户端都会实时收到新消息! 🎉

4. 为特定用户筛选订阅事件 🎯

问题: 在许多现实世界的应用程序中,您不希望将每个事件广播给每个订阅的客户端。例如,在一个私人聊天中,只有参与对话的用户才能看到新消息。

解决方案: 大多数 GraphQL 订阅实现都允许您根据特定条件筛选事件。这通常是通过向订阅解析器添加一个 filter 函数来完成的。

这个 filter 函数通常接收两个参数:

  • payload: 由 pubsub.publish() 发出的事件数据。
  • variables: 客户端在发起订阅时传递的变量。

该函数应返回一个布尔值,指示是否应将更新推送到特定客户端。

示例:

假设我们只想通知特定聊天室中的用户。

架构定义 (SDL):

graphql
type Subscription {
  newMessage(roomId: ID!): Message!
}

解析器:

javascript
import { pubsub } from './pubsub';
import { withFilter } from 'graphql-subscriptions';

const resolvers = {
  Subscription: {
    newMessage: {
      subscribe: withFilter(
        () => pubsub.asyncIterator('NEW_MESSAGE'),
        (payload, variables) => {
          // 仅在消息的 roomId 与客户端订阅的 roomId 匹配时才推送更新
          return payload.newMessage.roomId === variables.roomId;
        }
      )
    }
  },
  Mutation: {
    createMessage: (parent, { text, roomId }) => {
      const message = { id: Date.now().toString(), text, roomId };
      pubsub.publish('NEW_MESSAGE', { newMessage: message });
      return message;
    }
  }
};

在这个例子中,我们使用了 graphql-subscriptions 包中的 withFilter 帮助函数。它将我们的 asyncIterator 与一个过滤器函数包装在一起。现在,只有当已发布消息的 roomId 与客户端订阅时提供的 roomId 相匹配时,客户端才会收到更新。

这为您在谁可以实时接收哪些数据方面提供了强大的控制,确保了隐私和效率。

总结

恭喜!您现在已经了解了 GraphQL 订阅的基础知识。您已经了解了它们如何与 WebSocket 协同工作以提供实时数据,如何使用 PubSub 系统发出和侦听事件,如何从突变中触发这些事件,以及如何筛选这些事件以仅将其发送给相关用户。

掌握了这些知识,您就可以构建动态和引人入胜的应用程序,让您的用户保持最新状态。 🚀


📚 额外阅读和参考资料

Challenge

You are building a real-time notification system for a multi-category blog. Your task is to implement the GraphQL backend logic that allows clients to subscribe to new post notifications for a specific category.

Requirements:

  1. Schema Definition (typeDefs):

    • Define a Post type with the following fields: id: ID!, content: String!, and category: String!.
    • Define a Query type with a placeholder field (e.g., _empty: String). A valid schema requires a Query type.
    • Define a Mutation named createPost that accepts content: String! and category: String! as arguments and returns the newly created Post.
    • Define a Subscription named newPost that accepts a category: String! argument and streams Post objects.
  2. Resolver Implementation (resolvers):

    • Implement the createPost mutation resolver. This function should simulate creating a post, and then publish an event to a topic named NEW_POST. The payload of the event must be an object with a single key, newPost, containing the created post object.
    • Implement the newPost subscription resolver. You must use the withFilter utility to ensure that subscribers only receive posts matching the category they subscribed to. The filter logic should compare the category from the incoming payload with the category variable provided by the client's subscription.

Expected result

Your final code should consist of a GraphQL schema string (typeDefs) and a resolvers object that correctly implement the real-time notification logic.

typeDefs

The schema string should define the Post, Query, Mutation, and Subscription types as specified. The createPost mutation must accept content and category strings and return a Post. The newPost subscription must accept a category string and return a Post stream.

resolvers

The resolvers object must contain:

  1. A Mutation.createPost resolver that:
    • Creates a new post object, including a unique ID.
    • Publishes the new post to the NEW_POST topic using pubsub.publish().
    • Returns the newly created post object.
  2. A Subscription.newPost resolver that:
    • Is an object with a subscribe property.
    • The subscribe property's value is the result of calling withFilter.
    • withFilter is called with two arguments: () => pubsub.asyncIterator(['NEW_POST']), and a filter function.
    • The filter function (payload, variables) => { ... } must return true only when payload.newPost.category is strictly equal to variables.category.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.