Subscription GraphQL untuk Data Real-Time
Tambahkan kemampuan real-time ke API GraphQL Anda menggunakan subscription, sehingga klien menerima pembaruan langsung melalui WebSockets saat data berubah.
Subscription GraphQL untuk Data Real-Time adalah pelajaran Node.js Backend Development Bootcamp gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Node.js Backend Development Bootcamp, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Node.js Backend Development Bootcamp mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
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.
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Subscription GraphQL untuk Data Real-Time” gratis?
Ya — teks lengkap “Subscription GraphQL untuk Data Real-Time” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Node.js Backend Development Bootcamp, upgrade ke CoddyKit PRO. Kursus Node.js Backend Development Bootcamp mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Subscription GraphQL untuk Data Real-Time”?
Tambahkan kemampuan real-time ke API GraphQL Anda menggunakan subscription, sehingga klien menerima pembaruan langsung melalui WebSockets saat data berubah. Kamu berlatih Node.js Backend Development Bootcamp dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai Node.js Backend Development Bootcamp?
Tidak diperlukan pengalaman sebelumnya. Node.js Backend Development Bootcamp di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Subscription GraphQL untuk Data Real-Time” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran Node.js Backend Development Bootcamp ini?
Ya. Setiap pelajaran Node.js Backend Development Bootcamp menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Pengantar Serverless dengan Node.js
- Prinsip Desain API GraphQL
- Membangun Server GraphQL dengan Apollo
- Subscription GraphQL untuk Data Real-Time