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 }) => {
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 return { txid: response.txid }
41 },
42 onUpdate: async ({ transaction }) => {
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 return { txid: txids }
54 },
55 onDelete: async ({ transaction }) => {
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 return { txid: txids }
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 }) => {
89 const {
90 id: _id,
91 created_at: _crea,
92 updated_at: _up,
93 ...modified
94 } = transaction.mutations[0].modified
95 return await api.todos.create(modified)
96 },
97 onUpdate: async ({ transaction }) => {
98 return await Promise.all(
99 transaction.mutations.map(async (mutation) => {
100 const { original, changes } = mutation
101 if (!(`id` in original)) {
102 throw new Error(`Original todo not found for update`)
103 }
104 return await api.todos.update(original.id, changes)
105 })
106 )
107 },
108 onDelete: async ({ transaction }) => {
109 return await Promise.all(
110 transaction.mutations.map(async (mutation) => {
111 const { original } = mutation
112 if (!(`id` in original)) {
113 throw new Error(`Original todo not found for delete`)
114 }
115 await api.todos.delete(original.id)
116 })
117 )
118 },
119 })
120)
121
122type Todo = {
123 id: number
124 text: string
125 completed: boolean
126 created_at: number
127 updated_at: number
128}
129
130// TrailBase Todo Collection
131export const trailBaseTodoCollection = createCollection(
132 trailBaseCollectionOptions<SelectTodo, Todo>({
133 id: `todos`,
134 getKey: (item) => item.id,
135 schema: selectTodoSchema,
136 recordApi: trailBaseClient.records(`todos`),
137 // Re-using the example's drizzle-schema requires remapping the items.
138 parse: {
139 created_at: (ts) => new Date(ts * 1000),
140 updated_at: (ts) => new Date(ts * 1000),
141 },
142 serialize: {
143 created_at: (date) => Math.floor(date.valueOf() / 1000),
144 updated_at: (date) => Math.floor(date.valueOf() / 1000),
145 },
146 })
147)
148
149// Electric Config Collection
150export const electricConfigCollection = createCollection(
151 electricCollectionOptions({
152 id: `config`,
153 shapeOptions: {
154 url: `http://localhost:3003/v1/shape`,
155 params: {
156 table: `config`,
157 },
158 parser: {
159 timestamptz: (date: string) => new Date(date),
160 },
161 },
162 getKey: (item) => item.id,
163 schema: selectConfigSchema,
164 onInsert: async ({ transaction }) => {
165 const modified = transaction.mutations[0].modified
166 const response = await api.config.create(modified)
167 return { txid: response.txid }
168 },
169 onUpdate: async ({ transaction }) => {
170 const txids = await Promise.all(
171 transaction.mutations.map(async (mutation) => {
172 const { original, changes } = mutation
173 if (!(`id` in original)) {
174 throw new Error(`Original config not found for update`)
175 }
176 const response = await api.config.update(original.id, changes)
177 return response.txid
178 })
179 )
180 return { txid: txids }
181 },
182 })
183)
184
185// Query Config Collection
186export const queryConfigCollection = createCollection(
187 queryCollectionOptions({
188 id: `config`,
189 queryKey: [`config`],
190 refetchInterval: 3000,
191 queryFn: async () => {
192 const configs = await api.config.getAll()
193 return configs.map((config) => ({
194 ...config,
195 created_at: new Date(config.created_at),
196 updated_at: new Date(config.updated_at),
197 }))
198 },
199 getKey: (item) => item.id,
200 schema: selectConfigSchema,
201 queryClient,
202 onInsert: async ({ transaction }) => {
203 const modified = transaction.mutations[0].modified
204 const response = await api.config.create(modified)
205 return { txid: response.txid }
206 },
207 onUpdate: async ({ transaction }) => {
208 const txids = await Promise.all(
209 transaction.mutations.map(async (mutation) => {
210 const { original, changes } = mutation
211 if (!(`id` in original)) {
212 throw new Error(`Original config not found for update`)
213 }
214 const response = await api.config.update(original.id, changes)
215 return response.txid
216 })
217 )
218 return { txid: txids }
219 },
220 })
221)
222
223type Config = {
224 id: number
225 key: string
226 value: string
227 created_at: number
228 updated_at: number
229}
230
231// TrailBase Config Collection
232export const trailBaseConfigCollection = createCollection(
233 trailBaseCollectionOptions<SelectConfig, Config>({
234 id: `config`,
235 getKey: (item) => item.id,
236 schema: selectConfigSchema,
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)