0Pricing
Node.js Backend Development Bootcamp · Lekcja

Subskrypcje GraphQL dla danych w czasie rzeczywistym

Dodaj do API GraphQL funkcje czasu rzeczywistego za pomocą subskrypcji, aby klienci otrzymywali aktualizacje przez WebSockets natychmiast po zmianie danych.

Subskrypcje GraphQL dla danych w czasie rzeczywistym to bezpłatna lekcja Node.js Backend Development Bootcamp na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Node.js Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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 Subscription type and resolve it with asyncIterator
  • Mutations publish events; withFilter targets 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.

Często zadawane pytania

Czy lekcja „Subskrypcje GraphQL dla danych w czasie rzeczywistym” jest bezpłatna?

Tak — pełny tekst „Subskrypcje GraphQL dla danych w czasie rzeczywistym” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Node.js Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.

Co nauczysz się w „Subskrypcje GraphQL dla danych w czasie rzeczywistym”?

Dodaj do API GraphQL funkcje czasu rzeczywistego za pomocą subskrypcji, aby klienci otrzymywali aktualizacje przez WebSockets natychmiast po zmianie danych. Ćwiczysz Node.js Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Node.js Backend Development Bootcamp?

Nie wymagamy żadnego doświadczenia. Node.js Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Subskrypcje GraphQL dla danych w czasie rzeczywistym”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Node.js Backend Development Bootcamp?

Tak. Każda lekcja Node.js Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Wprowadzenie do serverless z Node.js
  2. Zasady projektowania API GraphQL
  3. Tworzenie serwera GraphQL z Apollo
  4. Subskrypcje GraphQL dla danych w czasie rzeczywistym
← Powrót do Node.js Backend Development Bootcamp