TypeScript v4 SDKs now stream server-sent events. An operation whose success response is text/event-stream resolves to an EventStream<T> typed over the event's data schema, and you read it with for await.
Details
The call resolves as soon as the response headers arrive, and events are read from the connection only as your loop asks for them. Each iteration yields one event's data, already decoded: a string, a model, an array, or a discriminated union you narrow on its kind. The stream ends cleanly on the sentinel named by the x-sse-sentinel extension, which is consumed and never yielded, or when the server closes the connection.
Draining the loop releases the connection, and so does leaving it early with break, return or a throw. A stream you decide not to read is released with await stream.close(), or with await using where your runtime supports it, and aborting the signal you passed stops it from elsewhere.
The loop raises the same error family as the call itself: a DecodeError for an event whose data does not fit the schema, a ConnectionError when the connection drops, and a TimeoutError when the server stays silent for longer than the eventStream.idleTimeout client option, which defaults to 60 seconds. An error status rejects the call with ApiError before any event is read, and .asApiResult() gives you the opening status and headers of the stream.
Usage Example
Iterate the stream, and stop as soon as you have what you need:
import { PaymentsClient, PaymentsError } from "payments";
const client = new PaymentsClient({ eventStream: { idleTimeout: 30_000 } });
try {
const updates = await client.payments.streamUpdates({ paymentId: "pay_123" });
// Each event's data arrives as a typed model; breaking out releases the connection.
for await (const update of updates) {
console.log(update.status);
if (update.settledAt) break;
}
} catch (err) {
if (err instanceof PaymentsError) {
console.error(`${err.kind}: ${err.message}`);
} else {
throw err;
}
}
Put the try around the loop, not only the call, because the call settles as soon as the headers arrive.
This feature is available in the TypeScript v4 SDK. Generate it with version 2.x of the APIMatic CLI:
apimatic sdk generate --language=typescript
For the full set of flags and options, see the APIMatic CLI documentation.