feat: SSE and ndjson stream encoders
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+50
No files matched your search
@@ -0,0 +1,21 @@
|
|||||||
|
export interface StreamEncoder {
|
||||||
|
headers: Record<string, string>;
|
||||||
|
encode(item: unknown): string | Buffer;
|
||||||
|
encodeError(err: unknown): string | Buffer | null;
|
||||||
|
ping?(): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const msgOf = (e: unknown): string => (e instanceof Error ? e.message : String(e));
|
||||||
|
|
||||||
|
export const sseEncoder: StreamEncoder = {
|
||||||
|
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
|
||||||
|
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
|
||||||
|
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: msgOf(err) })}\n\n`,
|
||||||
|
ping: () => ': ping\n\n',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ndjsonEncoder: StreamEncoder = {
|
||||||
|
headers: { 'content-type': 'application/x-ndjson' },
|
||||||
|
encode: (item) => `${JSON.stringify(item)}\n`,
|
||||||
|
encodeError: (err) => `${JSON.stringify({ error: msgOf(err) })}\n`,
|
||||||
|
};
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { sseEncoder, ndjsonEncoder } from '../src/encoders';
|
||||||
|
|
||||||
|
describe('sseEncoder', () => {
|
||||||
|
it('frames data as SSE events', () => {
|
||||||
|
expect(sseEncoder.encode({ a: 1 })).toBe('data: {"a":1}\n\n');
|
||||||
|
});
|
||||||
|
it('frames errors as an SSE error event with only the message', () => {
|
||||||
|
expect(sseEncoder.encodeError(new Error('nope'))).toBe('event: error\ndata: {"error":"nope"}\n\n');
|
||||||
|
});
|
||||||
|
it('sets text/event-stream headers and has a ping', () => {
|
||||||
|
expect(sseEncoder.headers['content-type']).toBe('text/event-stream');
|
||||||
|
expect(typeof sseEncoder.ping).toBe('function');
|
||||||
|
expect(sseEncoder.ping!()).toBe(': ping\n\n');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ndjsonEncoder', () => {
|
||||||
|
it('frames one JSON line per item', () => {
|
||||||
|
expect(ndjsonEncoder.encode({ a: 1 })).toBe('{"a":1}\n');
|
||||||
|
});
|
||||||
|
it('frames errors as a terminal JSON line', () => {
|
||||||
|
expect(ndjsonEncoder.encodeError(new Error('nope'))).toBe('{"error":"nope"}\n');
|
||||||
|
});
|
||||||
|
it('sets ndjson content-type and has no ping', () => {
|
||||||
|
expect(ndjsonEncoder.headers['content-type']).toBe('application/x-ndjson');
|
||||||
|
expect(ndjsonEncoder.ping).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user