Guides
Subscriptions
On this page
graphql-js expects a subscription field to return an AsyncIterable, so Gratos requires subscription fields to return an AsyncIterable<T>, or an Effect Stream.Stream<A, E, R>, which the server's Effect layer runs (below). Beyond that, there is nothing special about subscriptions.
Example
import type { Int } from "gratos";
/** @gqlSubscriptionField */
export async function* countdown(): AsyncIterable<Int> {
for (let i = 10; i >= 0; i--) {
await sleep(1);
yield i;
}
}
function sleep(s: number) {
return new Promise((resolve) => setTimeout(resolve, s * 1000));
}
// graphql-js serves no schema without a query type, so this one has a query field too.
/** @gqlQueryField */
export function ping(): string {
return "pong";
}type Query {
ping: String
}
type Subscription {
countdown: Int
}Effect streams
In Gratos, a subscription field may also return an Effect Stream.Stream<A, E, R>, one event per item: the server's Effect layer runs it with the request's services, and interrupts it when the client leaves. A subscription never returns an Effect.Effect. See Effect resolvers.
Serving subscriptions
gratos-server serves subscriptions over server-sent events, with no plugin to add (see Streams).