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

electric.test-d.ts

288 lines8.6 KB

1import { describe, expectTypeOf, it } from "vitest"
2import { z } from "zod"
3import {
4 createCollection,
5 createLiveQueryCollection,
6 eq,
7 gt,
8} from "@tanstack/db"
9import { electricCollectionOptions } from "../src/electric"
10import type { ElectricCollectionConfig } from "../src/electric"
11import type {
12 DeleteMutationFnParams,
13 InsertMutationFnParams,
14 UpdateMutationFnParams,
15} from "@tanstack/db"
16​
17describe(`Electric collection type resolution tests`, () => {
18 // Define test types
19 type ExplicitType = { id: string; explicit: boolean }
20 type FallbackType = { id: string; fallback: boolean }
21​
22 // Define a schema
23 const testSchema = z.object({
24 id: z.string(),
25 schema: z.boolean(),
26 })
27​
28 type SchemaType = z.infer<typeof testSchema>
29​
30 it(`should prioritize explicit type in ElectricCollectionConfig`, () => {
31 const options = electricCollectionOptions<ExplicitType>({
32 shapeOptions: {
33 url: `foo`,
34 params: { table: `test_table` },
35 },
36 getKey: (item) => item.id,
37 })
38​
39 // The getKey function should have the resolved type
40 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExplicitType]>()
41 })
42​
43 it(`should use schema type when a schema is provided`, () => {
44 const options = electricCollectionOptions({
45 shapeOptions: {
46 url: `foo`,
47 params: { table: `test_table` },
48 },
49 schema: testSchema,
50 getKey: (item) => item.id,
51 })
52​
53 // The getKey function should have the resolved type
54 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[SchemaType]>()
55 })
56​
57 it(`should throw a type error when both a schema and an explicit type (that is not the type of the schema) are provided`, () => {
58 electricCollectionOptions<ExplicitType>({
59 shapeOptions: {
60 url: `foo`,
61 params: { table: `test_table` },
62 },
63 // @ts-expect-error – schema should be `undefined` because we passed an explicit type
64 schema: testSchema,
65 getKey: (item) => item.id,
66 })
67 })
68​
69 it(`should use explicit type when no schema is provided`, () => {
70 const config: ElectricCollectionConfig<FallbackType> = {
71 shapeOptions: {
72 url: `foo`,
73 params: { table: `test_table` },
74 },
75 getKey: (item) => item.id,
76 }
77​
78 const options = electricCollectionOptions(config)
79​
80 // The getKey function should have the resolved type
81 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[FallbackType]>()
82 })
83​
84 it(`should use getKey type when no schema and no explicit type is provided`, () => {
85 const config = {
86 shapeOptions: {
87 url: `foo`,
88 params: { table: `test_table` },
89 },
90 getKey: (item: FallbackType) => item.id,
91 }
92​
93 const options = electricCollectionOptions(config)
94​
95 // The getKey function should have the resolved type
96 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[FallbackType]>()
97 })
98​
99 it(`should properly type the onInsert, onUpdate, and onDelete handlers`, () => {
100 const options = electricCollectionOptions<ExplicitType>({
101 shapeOptions: {
102 url: `test_shape`,
103 params: { table: `test_table` },
104 },
105 getKey: (item) => item.id,
106 onInsert: (params) => {
107 // Verify that the mutation value has the correct type
108 expectTypeOf(
109 params.transaction.mutations[0].modified
110 ).toEqualTypeOf<ExplicitType>()
111 return Promise.resolve({ txid: 1 })
112 },
113 onUpdate: (params) => {
114 // Verify that the mutation value has the correct type
115 expectTypeOf(
116 params.transaction.mutations[0].modified
117 ).toEqualTypeOf<ExplicitType>()
118 return Promise.resolve({ txid: 1 })
119 },
120 onDelete: (params) => {
121 // Verify that the mutation value has the correct type
122 expectTypeOf(
123 params.transaction.mutations[0].original
124 ).toEqualTypeOf<ExplicitType>()
125 return Promise.resolve({ txid: 1 })
126 },
127 })
128​
129 // Verify that the handlers are properly typed
130 expectTypeOf(options.onInsert).parameters.toEqualTypeOf<
131 [InsertMutationFnParams<ExplicitType>]
132 >()
133​
134 expectTypeOf(options.onUpdate).parameters.toEqualTypeOf<
135 [UpdateMutationFnParams<ExplicitType>]
136 >()
137​
138 expectTypeOf(options.onDelete).parameters.toEqualTypeOf<
139 [DeleteMutationFnParams<ExplicitType>]
140 >()
141 })
142​
143 it(`should infer types from Zod schema through electric collection options to live query`, () => {
144 // Define a Zod schema for a user with basic field types
145 const userSchema = z.object({
146 id: z.string(),
147 name: z.string(),
148 age: z.number(),
149 email: z.string().email(),
150 active: z.boolean(),
151 })
152​
153 type UserType = z.infer<typeof userSchema>
154​
155 // Create electric collection options with the schema
156 const electricOptions = electricCollectionOptions({
157 shapeOptions: {
158 url: `test_shape`,
159 params: { table: `users` },
160 },
161 schema: userSchema,
162 getKey: (item) => item.id,
163 })
164​
165 // Create a collection using the electric options
166 const usersCollection = createCollection(electricOptions)
167​
168 // Create a live query collection that uses the users collection
169 const activeUsersQuery = createLiveQueryCollection({
170 query: (q) =>
171 q
172 .from({ user: usersCollection })
173 .where(({ user }) => eq(user.active, true))
174 .select(({ user }) => ({
175 id: user.id,
176 name: user.name,
177 age: user.age,
178 email: user.email,
179 isActive: user.active,
180 })),
181 })
182​
183 // Test that the query results have the correct inferred types
184 const results = activeUsersQuery.toArray
185 expectTypeOf(results).toEqualTypeOf<
186 Array<{
187 id: string
188 name: string
189 age: number
190 email: string
191 isActive: boolean
192 }>
193 >()
194​
195 // Test that the collection itself has the correct type
196 expectTypeOf(usersCollection.toArray).toEqualTypeOf<Array<UserType>>()
197​
198 // Test that we can access schema-inferred fields in the query with WHERE conditions
199 const ageFilterQuery = createLiveQueryCollection({
200 query: (q) =>
201 q
202 .from({ user: usersCollection })
203 .where(({ user }) => eq(user.active, true) && gt(user.age, 18))
204 .select(({ user }) => ({
205 id: user.id,
206 name: user.name,
207 age: user.age,
208 })),
209 })
210​
211 const ageFilterResults = ageFilterQuery.toArray
212 expectTypeOf(ageFilterResults).toEqualTypeOf<
213 Array<{
214 id: string
215 name: string
216 age: number
217 }>
218 >()
219​
220 // Test that the getKey function has the correct parameter type
221 expectTypeOf(electricOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
222 })
223​
224 it(`should demonstrate the difference between electric options and direct createCollection with schema`, () => {
225 // Define a Zod schema with basic fields
226 const userSchema = z.object({
227 id: z.string(),
228 name: z.string(),
229 age: z.number(),
230 email: z.string().email(),
231 active: z.boolean(),
232 })
233​
234 type UserType = z.infer<typeof userSchema>
235​
236 // Method 1: Using electric collection options (WORKS)
237 const electricOptions = electricCollectionOptions({
238 shapeOptions: {
239 url: `test_shape`,
240 params: { table: `users` },
241 },
242 schema: userSchema,
243 getKey: (item) => item.id,
244 })
245​
246 const electricCollection = createCollection(electricOptions)
247​
248 // Method 2: Using direct createCollection with schema (FAILS with never types)
249 const directCollection = createCollection({
250 id: `test-direct`,
251 schema: userSchema,
252 getKey: (item) => item.id,
253 sync: {
254 sync: ({ begin, commit, markReady }) => {
255 begin()
256 commit()
257 markReady()
258 },
259 },
260 })
261​
262 // Test that electric collection works correctly
263 const electricQuery = createLiveQueryCollection({
264 query: (q) =>
265 q.from({ user: electricCollection }).select(({ user }) => ({
266 id: user.id,
267 name: user.name,
268 age: user.age,
269 })),
270 })
271​
272 const electricResults = electricQuery.toArray
273 expectTypeOf(electricResults).toEqualTypeOf<
274 Array<{
275 id: string
276 name: string
277 age: number
278 }>
279 >()
280​
281 // Test that direct collection has the correct type
282 expectTypeOf(directCollection.toArray).toEqualTypeOf<Array<UserType>>()
283​
284 // The key insight: electric collection options properly resolve schema types
285 // while direct createCollection with schema doesn't work in query builder
286 expectTypeOf(electricOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
287 })
288})