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

ssr-fixture.ts

108 lines2.3 KB

1import { DbClient, collectionOptions, eq } from '@tanstack/react-db'
2import type { DehydratedDbState } from '@tanstack/react-db'
3​
4export type SsrTodo = {
5 id: string
6 text: string
7 status: `open` | `done`
8 source: `server` | `sync` | `stream`
9}
10​
11export const ssrTodoCollectionId = `ssr-e2e-todos`
12​
13const serverTodos: Array<SsrTodo> = [
14 {
15 id: `server-1`,
16 text: `Pay invoices`,
17 status: `open`,
18 source: `server`,
19 },
20 {
21 id: `server-2`,
22 text: `Review pull requests`,
23 status: `open`,
24 source: `server`,
25 },
26 {
27 id: `server-3`,
28 text: `Archived roadmap`,
29 status: `done`,
30 source: `server`,
31 },
33​
34const browserTodos: Array<SsrTodo> = serverTodos.map((todo) =>
35 todo.id === `server-1`
36 ? {
37 ...todo,
38 text: `Pay invoices (reconciled from sync)`,
39 source: `sync`,
40 }
41 : { ...todo, source: `sync` },
43​
44export const streamedTodo: SsrTodo = {
45 id: `streamed-1`,
46 text: `Streamed from collection chunk`,
47 status: `open`,
48 source: `stream`,
50​
51export const ssrTodoCollection = collectionOptions(ssrTodoCollectionId, () => ({
52 id: ssrTodoCollectionId,
53 getKey: (todo: SsrTodo) => todo.id,
54 syncMode: `on-demand`,
55 sync: {
56 sync: ({ begin, write, commit, markReady }) => {
57 markReady()
58​
59 return {
60 loadSubset: () => {
61 const todos =
62 typeof window === `undefined` ? serverTodos : browserTodos
63​
64 begin({ immediate: true })
65 for (const todo of todos) {
66 write({
67 type: `insert`,
68 value: todo,
69 })
70 }
71 commit()
72 return true
73 },
74 }
75 },
76 },
77}))
78​
79export async function preloadSsrTodos(dbClient: DbClient): Promise<void> {
80 await dbClient.preloadLiveQuery({
81 query: (q) =>
82 q
83 .from({ todo: ssrTodoCollection })
84 .where(({ todo }) => eq(todo.status, `open`)),
85 })
87​
88export async function createDehydratedSsrTodoState(): Promise<DehydratedDbState> {
89 const dbClient = new DbClient()
90 try {
91 await preloadSsrTodos(dbClient)
92 return dbClient.dehydrate()
93 } finally {
94 await dbClient.cleanup()
95 }
97​
98export function applyStreamedTodo(dbClient: DbClient): void {
99 dbClient.applyCollectionChunk({
100 collectionId: ssrTodoCollectionId,
101 rows: [
102 {
103 key: streamedTodo.id,
104 value: streamedTodo,
105 },
106 ],
107 })