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

collections.ts

246 lines7.3 KB

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