Server-Sent Events (SSE)
You can handle an SSE stream by using the appropriate response contract.
ts
import { ResponseContract, useRouteBuilder } from "@duplojs/http";
import { D, DPE, sleep } from "@duplojs/utils";
useRouteBuilder("GET", "/some-route")
.extract({
headers: {
superToken: DPE.string(),
},
})
.cut(
ResponseContract.unauthorized("invalid-token"),
({ superToken }, { response, output }) => {
if (superToken !== "valid-token") {
return response("invalid-token");
}
return output();
},
)
.handler(
ResponseContract.serverSentEvents(
"SSE",
DPE.object({ value: DPE.string() }),
{ otherEvent: DPE.string() },
),
(__, { serverSentEventsResponse }) => serverSentEventsResponse(
"SSE",
async({ send, lastId, isAbort }) => {
if (lastId !== null) {
await send(
"otherEvent",
"successful reconnection",
{ retry: "10s" },
);
}
while (isAbort() === false) {
await send(
"message",
{ value: "super Value" },
{ id: D.now().toString() },
);
await sleep(1000);
}
},
),
);Handle the stream on the client
Just call a route that returns an SSE stream, and the client will create the appropriate response object to receive it.
ts
import { createHttpClient } from "@duplojs/http/client";
import { type Routes } from "./types";
const client = createHttpClient<Routes>({
baseUrl: "http://localhost:1506",
});
const response = await client.get(
"/some-route",
{ headers: { superToken: "valid-token" } },
).iWantInformationOrThrow("SSE");
response.onReceiveEvent("message", (event) => {
});
response.onReceiveEvent("otherEvent", (event) => {
// ...
});
// start consume SSE
for await (const event of response) {
// ...
}
// or
void response.consumeEventStream();When the client identifies an SSE stream, it adds methods to manipulate and consume the events it receives. To consume the stream, either iterate over the response or call consumeEventStream.
