Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

test-local-baseline.ts

73 lines2.2 KB

1import assert from 'node:assert/strict'
2import { mkdir, writeFile } from 'node:fs/promises'
3import { Shape, ShapeStream } from '../packages/client/src/index.js'
4​
5const url = process.env.SHAPE_URL ?? 'http://localhost:4327/api/shape'
6const abort = new AbortController()
7const timer = setTimeout(
8 () => abort.abort(new Error('Local baseline timed out')),
9 20_000
11const requests: { url: string; method: string }[] = []
12const start = performance.now()
13try {
14 const stream = new ShapeStream<{
15 id: number
16 label: string
17 enabled: boolean
18 }>({
19 url,
20 params: { table: 'electric_items' },
21 subscribe: false,
22 signal: abort.signal,
23 fetchClient: async (input, init) => {
24 const outward = String(input)
25 const target = new URL(outward)
26 assert.equal(target.origin, new URL(url).origin)
27 assert.equal(target.pathname, new URL(url).pathname)
28 requests.push({ url: outward, method: init?.method ?? 'GET' })
29 return fetch(input, init)
30 },
31 })
32 const shape = new Shape(stream)
33 const rows = await shape.rows
34 assert(
35 rows.some(
36 (row) =>
37 row.id === 1 && row.label === 'First item' && row.enabled === true
38 )
39 )
40 assert(stream.shapeHandle)
41 assert(stream.lastOffset !== '-1')
42 assert(requests.every((r) => r.method === 'GET'))
43 const resumed = new URL(url)
44 resumed.searchParams.set('table', 'electric_items')
45 resumed.searchParams.set('handle', stream.shapeHandle)
46 resumed.searchParams.set('offset', stream.lastOffset)
47 const response = await fetch(resumed, { signal: abort.signal })
48 assert.equal(response.status, 200)
49 assert.deepEqual(await response.json(), [])
50 assert(response.headers.has('electric-schema'))
51 await mkdir('.artifacts/staging', { recursive: true })
52 await writeFile(
53 '.artifacts/staging/local-baseline.json',
54 JSON.stringify(
55 {
56 rows,
57 requests,
58 handle: stream.shapeHandle,
59 offset: stream.lastOffset,
60 elapsedMs: performance.now() - start,
61 resumeStatus: response.status,
62 },
63 null,
64 2
65 )
66 )
67 console.log(
68 `Local neon dev baseline passed (${rows.length} rows, ${requests.length} GETs, saved-offset tail resume)`
69 )
70} finally {
71 clearTimeout(timer)
72 abort.abort()