Skip to content
This repository has been archived by the owner on Jul 5, 2024. It is now read-only.

Commit

Permalink
cool SSE bruv
Browse files Browse the repository at this point in the history
  • Loading branch information
KATT committed Oct 13, 2023
1 parent d8a740c commit bb0e688
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/async/asyncTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export type TsonAsyncStringifierIterable<TValue> = AsyncIterable<string> & {
[serialized]: TValue;
};

export type BrandSerialized<TType, TValue> = TType & {
[serialized]: TValue;
};

export type TsonAsyncStringifier = <TValue>(
value: TValue,
space?: number,
Expand Down
38 changes: 38 additions & 0 deletions src/async/serializeAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
TsonTypeTesterPrimitive,
} from "../sync/syncTypes.js";
import {
BrandSerialized,
TsonAsyncIndex,
TsonAsyncOptions,
TsonAsyncStringifier,
Expand Down Expand Up @@ -246,3 +247,40 @@ export function createTsonStreamAsync(

return stringifier as TsonAsyncStringifier;
}

export function crateTsonSSEResponse(opts: TsonAsyncOptions) {
const serialize = createAsyncTsonSerialize(opts);

return <TValue>(value: TValue) => {
let controller: ReadableStreamDefaultController<unknown> =
null as unknown as ReadableStreamDefaultController<unknown>;
const readable = new ReadableStream<unknown>({
start(c) {
controller = c;
},
});

async function iterate() {
const [head, iterable] = serialize(value);

controller.enqueue(`data: ${JSON.stringify(head)}\n\n`);
for await (const chunk of iterable) {
controller.enqueue(`data: ${JSON.stringify(chunk)}`);
}
}

iterate().catch((err) => {
controller.error(err);
});

const res = new Response(readable, {
headers: {
"Cache-Control": "no-cache",
Connection: "keep-alive",
"Content-Type": "text/event-stream",
},
status: 200,
});
return res as BrandSerialized<typeof res, TValue>;
};
}

0 comments on commit bb0e688

Please sign in to comment.