Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

backend.ts

55 lines1.9 KB

1import type { Row, Scope } from './model-oracle.js'
2​
3export type Page<T> = { rows: Array<T>; nextCursor: string | null }
4export type FetchPage<T> = (
5 cursor: string | undefined,
6 signal?: AbortSignal,
7) => Promise<Page<T>>
8​
9let nextSequence = 0
10​
11/** Backend token table is private to the fixture; the pager cannot decode it. */
12export function createBackend(
13 source: ReadonlyArray<Row>,
14 scope: Scope,
15 pageSize: number,
16 emptyFirst = false,
17) {
18 const sequence = ++nextSequence
19 const rows: Array<Row> = []
20 // Separate formulation from the model's filter/sort/slice. The backend's
21 // trusted job is to expose one stable relation in opaque, finite pages.
22 for (const row of source) {
23 if (scope.group !== undefined && row.group !== scope.group) continue
24 const position = rows.findIndex((other) => {
25 const before =
26 row.rank < other.rank || (row.rank === other.rank && row.id < other.id)
27 return scope.descending ? !before : before
28 })
29 rows.splice(position < 0 ? rows.length : position, 0, { ...row })
30 }
31 const tokens = new Map<string, number>()
32 let serial = 0
33 const calls: Array<string | undefined> = []
34 const token = (offset: number): string => {
35 const value = `opaque-${sequence}-${++serial}-${Math.imul(serial, 2654435761) >>> 0}`
36 tokens.set(value, offset)
37 return value
38 }
39 const fetchPage: FetchPage<Row> = (cursor, signal) => {
40 signal?.throwIfAborted()
41 calls.push(cursor)
42 if (emptyFirst && cursor === undefined) {
43 return Promise.resolve({ rows: [], nextCursor: token(0) })
44 }
45 const offset = cursor === undefined ? 0 : tokens.get(cursor)
46 if (offset === undefined) throw new Error(`Foreign or invented cursor`)
47 const page = rows.slice(offset, offset + pageSize)
48 const end = offset + page.length
49 return Promise.resolve({
50 rows: page.map((row) => ({ ...row })),
51 nextCursor: end < rows.length ? token(end) : null,
52 })
53 }
54 return { fetchPage, calls }