Guides
@stream
On this page
In a query, any list field is compatible with the @stream directive, even one that returns a plain array: the server sends the items after the first initialCount in later payloads. (graphql-js refuses an active @stream in a subscription operation.) To produce the items lazily, one at a time, define the field as returning an AsyncIterable<YourType>.
Example
/** @gqlType */
class Viewer {
/**
* An "algorithmically generated" feed of posts.
*
* **Note:** Due to the extreme complexity of this algorithm, it can be slow.
* It is recommended to use `@stream` to avoid blocking the client.
* @gqlField
*/
async *feed(ctx: Ctx): AsyncIterable<Post> {
const rows = await DB.selectPosts(ctx.vc);
for (const row of rows) {
// Simulate a slow algorithm
await new Promise((resolve) => setTimeout(resolve, 500));
yield new Post(row);
}
}
}
/** @gqlType */
class Post {
/** @gqlField */
id: string;
/** @gqlField */
title: string;
/** @gqlField */
content: string;
constructor(row: PostRow) {
this.id = row.id;
this.title = row.title;
this.content = row.content;
}
}
/** @gqlQueryField */
export function viewer(): Viewer {
return new Viewer();
}
/** @gqlContext */
type Ctx = { vc: ViewerContext };
type ViewerContext = { userId: string };
type PostRow = { id: string; title: string; content: string };
declare const DB: {
selectPosts(vc: ViewerContext): Promise<Array<PostRow>>;
};type Post {
content: String
id: String
title: String
}
type Query {
viewer: Viewer
}
type Viewer {
"""
An "algorithmically generated" feed of posts.
**Note:** Due to the extreme complexity of this algorithm, it can be slow.
It is recommended to use `@stream` to avoid blocking the client.
"""
feed: [Post!]
}A query can then read the field like this:
query ViewerFeedQuery {
viewer {
feed @stream {
id
title
content
}
}
}In Gratos, a streamed field's lazy source is an AsyncIterable, never an Effect Stream.Stream: a Stream.Stream is a subscription's source only, and the compiler rejects it on any other field (see The rules).
Enabling for your GraphQL server
Tip
Your GraphQL server must support @stream. In gratos-server, the incremental() plugin adds @defer and @stream, as in this site's server:
plugins: [
incremental(),See Plugins, and GraphQL over HTTP for the formats it sends.