-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathndjson-stream.ts
More file actions
68 lines (59 loc) · 1.55 KB
/
ndjson-stream.ts
File metadata and controls
68 lines (59 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import type { HattipHandler } from '@hattip/core'
import { createClient, createRouter } from 'rouzer'
import * as http from 'rouzer/http'
import * as ndjson from 'rouzer/ndjson'
type Event = {
id: number
message: string
}
export const events = http.get('events', {
response: ndjson.$type<Event>(),
})
export const routes = { events }
/**
* Tiny Hattip adapter used only to keep this example self-contained. Real apps
* mount the handler with a Hattip adapter for their runtime.
*/
function createLocalFetch(handler: HattipHandler): typeof fetch {
return async (input, init) => {
const request = new Request(input, init)
const response = await handler({
request,
ip: '127.0.0.1',
platform: undefined,
env() {
return undefined
},
passThrough() {},
waitUntil(promise) {
void promise
},
})
return response ?? new Response(null, { status: 404 })
}
}
async function collect<T>(source: AsyncIterable<T>) {
const values: T[] = []
for await (const value of source) {
values.push(value)
}
return values
}
export async function runNdjsonStreamExample() {
const handler = createRouter({
basePath: 'api/',
plugins: [ndjson.routerPlugin],
}).use(routes, {
async *events() {
yield { id: 1, message: 'ready' }
yield { id: 2, message: 'done' }
},
})
const client = createClient({
baseURL: 'https://example.test/api/',
routes,
plugins: [ndjson.clientPlugin],
fetch: createLocalFetch(handler),
})
return collect(await client.events())
}