リアルタイムデータ向けGraphQLサブスクリプション
サブスクリプションを使ってGraphQL APIにリアルタイム機能を追加し、データが変化した瞬間にWebSocket経由でクライアントが更新を受け取れるようにします。
「リアルタイムデータ向けGraphQLサブスクリプション」はCoddyKit上の無料Node.js Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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サブスクリプション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Node.js Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Node.js Backend Development Bootcampコースには全4レッスンが含まれています。
「リアルタイムデータ向けGraphQLサブスクリプション」で何を学びますか?
サブスクリプションを使ってGraphQL APIにリアルタイム機能を追加し、データが変化した瞬間にWebSocket経由でクライアントが更新を受け取れるようにします。 ブラウザで直接実行するハンズオンコードでNode.js Backend Development Bootcampを演習し、24時間対応の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サブスクリプション