用于实时数据的 GraphQL 订阅
使用订阅为您的 GraphQL API 添加实时能力,让客户端在数据变化时立即通过 WebSockets 接收实时更新
用于实时数据的 GraphQL 订阅 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Three GraphQL Operations
GraphQL defines three root operation types:
- Query: read data
- Mutation: change data
- Subscription: receive a stream of live updates
Queries and mutations are request/response; subscriptions keep a connection open for ongoing events.
When to Use Subscriptions
Subscriptions shine when clients need real-time data:
- Chat messages
- Live notifications
- Collaborative editing
- Live dashboards and scores
For data that rarely changes, polling a query is simpler.
WebSockets Under the Hood
Queries and mutations travel over HTTP, but subscriptions need a persistent two-way channel — a WebSocket. The server pushes events to subscribed clients without them asking again.
Defining a Subscription in the Schema
Add a Subscription type to your schema with fields clients can subscribe to. Each field is an event stream returning some type.
type Subscription {
messageAdded(channelId: ID!): Message!
}The PubSub Engine
Subscriptions rely on a publish/subscribe system. A PubSub instance lets your resolvers publish events and your subscriptions listen for them.
const { PubSub } = require('graphql-subscriptions');
const pubsub = new PubSub();Publishing an Event
Inside a mutation, after saving data, publish an event on a named topic. Anyone subscribed to that topic receives the payload.
const message = await Message.create(input);
pubsub.publish('MESSAGE_ADDED', { messageAdded: message });
return message;The Subscription Resolver
A subscription resolver returns an async iterator via asyncIterator, telling the server which topic to forward to the client.
const resolvers = {
Subscription: {
messageAdded: {
subscribe: () => pubsub.asyncIterator('MESSAGE_ADDED')
}
}
};Filtering Events
Often a client only cares about events for one channel. withFilter wraps the iterator and forwards only events that match the subscription's arguments.
const { withFilter } = require('graphql-subscriptions');
subscribe: withFilter(
() => pubsub.asyncIterator('MESSAGE_ADDED'),
(payload, vars) => payload.messageAdded.channelId === vars.channelId
)Client Subscription Query
The client writes a subscription operation just like a query, but with the subscription keyword. The server streams results as they happen.
subscription OnMessage($id: ID!) {
messageAdded(channelId: $id) {
id
text
}
}Scaling Across Servers
The in-memory PubSub only works on a single instance. To broadcast across many servers, swap in a backend like graphql-redis-subscriptions so events reach all connected clients.
const { RedisPubSub } = require('graphql-redis-subscriptions');
const pubsub = new RedisPubSub();Cleaning Up Connections
Open WebSockets consume resources. The server should detect disconnects and stop streaming. Apollo Server handles much of this, but watch for orphaned subscriptions and authenticate the connection on setup.
Quick Check
Test your GraphQL subscription knowledge.
Recap
You added real-time data with GraphQL subscriptions:
- Subscriptions stream live events over WebSockets
- Declare a
Subscriptiontype and resolve it withasyncIterator - Mutations
publishevents;withFiltertargets the right clients - Scale across servers with a Redis-backed PubSub and clean up connections
Now your API can power chat, notifications, and live dashboards.
常见问题解答
「用于实时数据的 GraphQL 订阅」课时是免费的吗?
是的 — 「用于实时数据的 GraphQL 订阅」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「用于实时数据的 GraphQL 订阅」这节课中我会学到什么?
使用订阅为您的 GraphQL API 添加实时能力,让客户端在数据变化时立即通过 WebSockets 接收实时更新 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「用于实时数据的 GraphQL 订阅」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Node.js 无服务器简介
- GraphQL API 设计原则
- 使用 Apollo 构建 GraphQL 服务器
- 用于实时数据的 GraphQL 订阅