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

collections.ts

230 lines6.9 KB

1import { createCollection } from '@tanstack/solid-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 const response = await api.todos.update(original.id, changes)
47 return response.txid
48 }),
49 )
50 await Promise.all(txids.map((txid) => collection.utils.awaitTxId(txid)))
51 },
52 onDelete: async ({ transaction, collection }) => {
53 const txids = await Promise.all(
54 transaction.mutations.map(async (mutation) => {
55 const { original } = mutation
56 const response = await api.todos.delete(original.id)
57 return response.txid
58 }),
59 )
60 await Promise.all(txids.map((txid) => collection.utils.awaitTxId(txid)))
61 },
62 }),
64​
65// Query Todo Collection
66export const queryTodoCollection = createCollection(
67 queryCollectionOptions({
68 id: `todos`,
69 queryKey: [`todos`],
70 refetchInterval: 3000,
71 queryFn: async () => {
72 const todos = await api.todos.getAll()
73 return todos.map((todo) => ({
74 ...todo,
75 created_at: new Date(todo.created_at),
76 updated_at: new Date(todo.updated_at),
77 }))
78 },
79 getKey: (item) => item.id,
80 schema: selectTodoSchema,
81 queryClient,
82 onInsert: async ({ transaction, collection }) => {
83 const {
84 id: _id,
85 created_at: _crea,
86 updated_at: _up,
87 ...modified
88 } = transaction.mutations[0].modified
89 await api.todos.create(modified)
90 await collection.utils.refetch()
91 },
92 onUpdate: async ({ transaction, collection }) => {
93 await Promise.all(
94 transaction.mutations.map(async (mutation) => {
95 const { original, changes } = mutation
96 return await api.todos.update(original.id, changes)
97 }),
98 )
99 await collection.utils.refetch()
100 },
101 onDelete: async ({ transaction, collection }) => {
102 await Promise.all(
103 transaction.mutations.map(async (mutation) => {
104 const { original } = mutation
105 await api.todos.delete(original.id)
106 }),
107 )
108 await collection.utils.refetch()
109 },
110 }),
112​
113type Todo = {
114 id: number
115 text: string
116 completed: boolean
117 created_at: number
118 updated_at: number
120​
121// TrailBase Todo Collection
122export const trailBaseTodoCollection = createCollection(
123 trailBaseCollectionOptions<SelectTodo, Todo>({
124 id: `todos`,
125 getKey: (item) => item.id,
126 recordApi: trailBaseClient.records(`todos`),
127 // Re-using the example's drizzle-schema requires remapping the items.
128 parse: {
129 created_at: (ts) => new Date(ts * 1000),
130 updated_at: (ts) => new Date(ts * 1000),
131 },
132 serialize: {
133 created_at: (date) => Math.floor(date.valueOf() / 1000),
134 updated_at: (date) => Math.floor(date.valueOf() / 1000),
135 },
136 }),
138​
139// Electric Config Collection
140export const electricConfigCollection = createCollection(
141 electricCollectionOptions({
142 id: `config`,
143 shapeOptions: {
144 url: `http://localhost:3003/v1/shape`,
145 params: {
146 table: `config`,
147 },
148 parser: {
149 timestamptz: (date: string) => new Date(date),
150 },
151 },
152 getKey: (item) => item.id,
153 schema: selectConfigSchema,
154 onInsert: async ({ transaction, collection }) => {
155 const modified = transaction.mutations[0].modified
156 const response = await api.config.create(modified)
157 await collection.utils.awaitTxId(response.txid)
158 },
159 onUpdate: async ({ transaction, collection }) => {
160 const txids = await Promise.all(
161 transaction.mutations.map(async (mutation) => {
162 const { original, changes } = mutation
163 const response = await api.config.update(original.id, changes)
164 return response.txid
165 }),
166 )
167 await Promise.all(txids.map((txid) => collection.utils.awaitTxId(txid)))
168 },
169 }),
171​
172// Query Config Collection
173export const queryConfigCollection = createCollection(
174 queryCollectionOptions({
175 id: `config`,
176 queryKey: [`config`],
177 refetchInterval: 3000,
178 queryFn: async () => {
179 const configs = await api.config.getAll()
180 return configs.map((config) => ({
181 ...config,
182 created_at: new Date(config.created_at),
183 updated_at: new Date(config.updated_at),
184 }))
185 },
186 getKey: (item) => item.id,
187 schema: selectConfigSchema,
188 queryClient,
189 onInsert: async ({ transaction, collection }) => {
190 const modified = transaction.mutations[0].modified
191 await api.config.create(modified)
192 await collection.utils.refetch()
193 },
194 onUpdate: async ({ transaction, collection }) => {
195 await Promise.all(
196 transaction.mutations.map(async (mutation) => {
197 const { original, changes } = mutation
198 await api.config.update(original.id, changes)
199 }),
200 )
201 await collection.utils.refetch()
202 },
203 }),
205​
206type Config = {
207 id: number
208 key: string
209 value: string
210 created_at: number
211 updated_at: number
213​
214// TrailBase Config Collection
215export const trailBaseConfigCollection = createCollection(
216 trailBaseCollectionOptions<SelectConfig, Config>({
217 id: `config`,
218 getKey: (item) => item.id,
219 recordApi: trailBaseClient.records(`config`),
220 // Re-using the example's drizzle-schema requires remapping the items.
221 parse: {
222 created_at: (ts) => new Date(ts * 1000),
223 updated_at: (ts) => new Date(ts * 1000),
224 },
225 serialize: {
226 created_at: (date) => Math.floor(date.valueOf() / 1000),
227 updated_at: (date) => Math.floor(date.valueOf() / 1000),
228 },
229 }),