Open History to see the last commit
1import { createCollection } from '@tanstack/react-db'
2import { electricCollectionOptions } from '@tanstack/electric-db-collection'
3import { queryCollectionOptions } from '@tanstack/query-db-collection'
4import { trailBaseCollectionOptions } from '@tanstack/trailbase-db-collection'
5import { QueryClient } from '@tanstack/query-core'
6import { initClient } from 'trailbase'
7import { selectConfigSchema, selectTodoSchema } from '../db/validation'
8import { api } from './api'
9import type { SelectConfig, SelectTodo } from '../db/validation'
10
11// Create a query client for query collections
12const queryClient = new QueryClient()
13
14// Create a TrailBase client.
15const trailBaseClient = initClient(`http://localhost:4000`)
16
17// Electric Todo Collection
18export const electricTodoCollection = createCollection(
19 electricCollectionOptions({
20 id: `todos`,
21 shapeOptions: {
22 url: `http://localhost:3003/v1/shape`,
23 params: {
24 table: `todos`,
25 },
26 parser: {
27 timestamptz: (date: string) => new Date(date),
28 },
29 },
30 getKey: (item) => item.id,
31 schema: selectTodoSchema,
32 onInsert: async ({ transaction, collection }) => {
33 const {
34 id: _id,
35 created_at: _f,
36 updated_at: _ff,
37 ...modified
38 } = transaction.mutations[0].modified
39 const response = await api.todos.create(modified)
40 await collection.utils.awaitTxId(response.txid)
41 },
42 onUpdate: async ({ transaction, collection }) => {
43 const txids = await Promise.all(
44 transaction.mutations.map(async (mutation) => {
45 const { original, changes } = mutation
46 if (!(`id` in original)) {
47 throw new Error(`Original todo not found for update`)
48 }
49 const response = await api.todos.update(original.id, changes)
50 return response.txid
51 }),
52 )
53 await Promise.all(txids.map((txid) => collection.utils.awaitTxId(txid)))
54 },
55 onDelete: async ({ transaction, collection }) => {
56 const txids = await Promise.all(
57 transaction.mutations.map(async (mutation) => {
58 const { original } = mutation
59 if (!(`id` in original)) {
60 throw new Error(`Original todo not found for delete`)
61 }
62 const response = await api.todos.delete(original.id)
63 return response.txid
64 }),
65 )
66 await Promise.all(txids.map((txid) => collection.utils.awaitTxId(txid)))
67 },
68 }),
69)
70
71// Query Todo Collection
72export const queryTodoCollection = createCollection(
73 queryCollectionOptions({
74 id: `todos`,
75 queryKey: [`todos`],
76 refetchInterval: 3000,
77 queryFn: async () => {
78 const todos = await api.todos.getAll()
79 return todos.map((todo) => ({
80 ...todo,
81 created_at: new Date(todo.created_at),
82 updated_at: new Date(todo.updated_at),
83 }))
84 },
85 getKey: (item) => item.id,
86 schema: selectTodoSchema,
87 queryClient,
88 onInsert: async ({ transaction, collection }) => {
89 const {
90 id: _id,
91 created_at: _crea,
92 updated_at: _up,
93 ...modified
94 } = transaction.mutations[0].modified
95 await api.todos.create(modified)
96 await collection.utils.refetch()
97 },
98 onUpdate: async ({ transaction, collection }) => {
99 await Promise.all(
100 transaction.mutations.map(async (mutation) => {
101 const { original, changes } = mutation
102 if (!(`id` in original)) {
103 throw new Error(`Original todo not found for update`)
104 }
105 return await api.todos.update(original.id, changes)
106 }),
107 )
108 await collection.utils.refetch()
109 },
110 onDelete: async ({ transaction, collection }) => {
111 await Promise.all(
112 transaction.mutations.map(async (mutation) => {
113 const { original } = mutation
114 if (!(`id` in original)) {
115 throw new Error(`Original todo not found for delete`)
116 }
117 await api.todos.delete(original.id)
118 }),
119 )
120 await collection.utils.refetch()
121 },
122 }),
123)
124
125type Todo = {
126 id: number
127 text: string
128 completed: boolean
129 created_at: number
130 updated_at: number
131}
132
133// TrailBase Todo Collection
134export const trailBaseTodoCollection = createCollection(
135 trailBaseCollectionOptions<SelectTodo, Todo>({
136 id: `todos`,
137 getKey: (item) => item.id,
138 recordApi: trailBaseClient.records(`todos`),
139 // Re-using the example's drizzle-schema requires remapping the items.
140 parse: {
141 created_at: (ts) => new Date(ts * 1000),
142 updated_at: (ts) => new Date(ts * 1000),
143 },
144 serialize: {
145 created_at: (date) => Math.floor(date.valueOf() / 1000),
146 updated_at: (date) => Math.floor(date.valueOf() / 1000),
147 },
148 }),
149)
150
151// Electric Config Collection
152export const electricConfigCollection = createCollection(
153 electricCollectionOptions({
154 id: `config`,
155 shapeOptions: {
156 url: `http://localhost:3003/v1/shape`,
157 params: {
158 table: `config`,
159 },
160 parser: {
161 timestamptz: (date: string) => new Date(date),
162 },
163 },
164 getKey: (item) => item.id,
165 schema: selectConfigSchema,
166 onInsert: async ({ transaction, collection }) => {
167 const modified = transaction.mutations[0].modified
168 const response = await api.config.create(modified)
169 await collection.utils.awaitTxId(response.txid)
170 },
171 onUpdate: async ({ transaction, collection }) => {
172 const txids = await Promise.all(
173 transaction.mutations.map(async (mutation) => {
174 const { original, changes } = mutation
175 if (!(`id` in original)) {
176 throw new Error(`Original config not found for update`)
177 }
178 const response = await api.config.update(original.id, changes)
179 return response.txid
180 }),
181 )
182 await Promise.all(txids.map((txid) => collection.utils.awaitTxId(txid)))
183 },
184 }),
185)
186
187// Query Config Collection
188export const queryConfigCollection = createCollection(
189 queryCollectionOptions({
190 id: `config`,
191 queryKey: [`config`],
192 refetchInterval: 3000,
193 queryFn: async () => {
194 const configs = await api.config.getAll()
195 return configs.map((config) => ({
196 ...config,
197 created_at: new Date(config.created_at),
198 updated_at: new Date(config.updated_at),
199 }))
200 },
201 getKey: (item) => item.id,
202 schema: selectConfigSchema,
203 queryClient,
204 onInsert: async ({ transaction, collection }) => {
205 const modified = transaction.mutations[0].modified
206 await api.config.create(modified)
207 await collection.utils.refetch()
208 },
209 onUpdate: async ({ transaction, collection }) => {
210 await Promise.all(
211 transaction.mutations.map(async (mutation) => {
212 const { original, changes } = mutation
213 if (!(`id` in original)) {
214 throw new Error(`Original config not found for update`)
215 }
216 await api.config.update(original.id, changes)
217 }),
218 )
219 await collection.utils.refetch()
220 },
221 }),
222)
223
224type Config = {
225 id: number
226 key: string
227 value: string
228 created_at: number
229 updated_at: number
230}
231
232// TrailBase Config Collection
233export const trailBaseConfigCollection = createCollection(
234 trailBaseCollectionOptions<SelectConfig, Config>({
235 id: `config`,
236 getKey: (item) => item.id,
237 recordApi: trailBaseClient.records(`config`),
238 // Re-using the example's drizzle-schema requires remapping the items.
239 parse: {
240 created_at: (ts) => new Date(ts * 1000),
241 updated_at: (ts) => new Date(ts * 1000),
242 },
243 serialize: {
244 created_at: (date) => Math.floor(date.valueOf() / 1000),
245 updated_at: (date) => Math.floor(date.valueOf() / 1000),
246 },
247 }),
248)