-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-custom-adapter.ts
More file actions
378 lines (320 loc) Β· 12.6 KB
/
test-custom-adapter.ts
File metadata and controls
378 lines (320 loc) Β· 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/**
* Test file for CustomAdapter
*
* This test uses JSONPlaceholder API (https://jsonplaceholder.typicode.com/)
* to verify CustomAdapter functionality.
*
* Run with: npx tsx test-custom-adapter.ts
*/
import { vibecodeTable, col, references, defineSchema, createClient, type DBSpec } from './packages/client/src'
import { CustomAdapter, createRESTHandlers } from './packages/client/src/adapters/custom'
import type { FilterOp } from './packages/client/src/core/types'
// Define schema using vibecode-db schema builder with proper references
const users = vibecodeTable('users', {
id: col.integer(),
name: col.varchar(),
username: col.varchar(),
email: col.varchar(),
phone: col.varchar(),
website: col.varchar(),
})
const posts = vibecodeTable('posts', {
id: col.integer(),
userId: references(col.integer('userId'), () => users.id),
title: col.varchar(),
body: col.varchar(),
})
const comments = vibecodeTable('comments', {
id: col.integer(),
postId: references(col.integer('postId'), () => posts.id),
name: col.varchar(),
email: col.varchar(),
body: col.varchar(),
})
const schema = defineSchema({ users, posts, comments })
const dbSpec: DBSpec<typeof schema.zodBundle.shape> = {
schema: schema.zodBundle,
relations: schema.relations,
}
const API_BASE = 'https://jsonplaceholder.typicode.com'
// Create client with CustomAdapter using manual implementation
const dbManual = createClient({
dbSpec,
adapter: (dbSpec) => new CustomAdapter(dbSpec, {
handlers: {
select: async (projection, ctx) => {
try {
console.log(`[SELECT] ${ctx.table}`, ctx.state)
let url = `${API_BASE}/${ctx.table}`
const params = new URLSearchParams()
// Apply filters (JSONPlaceholder supports simple equality filters)
for (const filter of ctx.state.filters) {
if (filter.type === 'eq') {
params.append(filter.column, String(filter.value))
}
}
// Add limit
if (ctx.state.limit) {
params.append('_limit', String(ctx.state.limit))
}
const queryString = params.toString()
if (queryString) url += `?${queryString}`
console.log(`[SELECT] Fetching: ${url}`)
const response = await fetch(url)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
let data = await response.json()
// Apply client-side filtering for unsupported operations
for (const filter of ctx.state.filters) {
if (filter.type === 'gt') {
data = data.filter((row: any) => row[filter.column] > (filter.value as number))
} else if (filter.type === 'lt') {
data = data.filter((row: any) => row[filter.column] < (filter.value as number))
} else if (filter.type === 'in') {
data = data.filter((row: any) => (filter.value as unknown[]).includes(row[filter.column]))
}
}
// Apply ordering client-side
if (ctx.state.order) {
const { column, ascending = true } = ctx.state.order
data.sort((a: any, b: any) => {
if (a[column] < b[column]) return ascending ? -1 : 1
if (a[column] > b[column]) return ascending ? 1 : -1
return 0
})
}
console.log(`[SELECT] Found ${data.length} rows`)
return { data, error: null }
} catch (error) {
console.error('[SELECT] Error:', error)
return { data: null, error: error as Error }
}
},
insert: async (values, ctx) => {
try {
console.log(`[INSERT] ${ctx.table}`, values)
const response = await fetch(`${API_BASE}/${ctx.table}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values),
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
const data = await response.json()
console.log(`[INSERT] Created:`, data)
return { data, error: null }
} catch (error) {
console.error('[INSERT] Error:', error)
return { data: null, error: error as Error }
}
},
update: async (patch, ctx) => {
try {
console.log(`[UPDATE] ${ctx.table}`, { patch, filters: ctx.state.filters })
// JSONPlaceholder requires ID in the URL
const idFilter = ctx.state.filters.find(f => f.column === 'id' && f.type === 'eq')
if (!idFilter) {
throw new Error('Update requires id filter')
}
const response = await fetch(`${API_BASE}/${ctx.table}/${idFilter.value}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch),
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
const data = await response.json()
console.log(`[UPDATE] Updated:`, data)
return { data: [data], error: null }
} catch (error) {
console.error('[UPDATE] Error:', error)
return { data: null, error: error as Error }
}
},
delete: async (ctx) => {
try {
console.log(`[DELETE] ${ctx.table}`, ctx.state.filters)
// JSONPlaceholder requires ID in the URL
const idFilter = ctx.state.filters.find(f => f.column === 'id' && f.type === 'eq')
if (!idFilter) {
throw new Error('Delete requires id filter')
}
const response = await fetch(`${API_BASE}/${ctx.table}/${idFilter.value}`, {
method: 'DELETE'
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
console.log(`[DELETE] Deleted successfully`)
return { data: null, error: null }
} catch (error) {
console.error('[DELETE] Error:', error)
return { data: null, error: error as Error }
}
}
},
onInit: async () => {
console.log('\nπ CustomAdapter initialized with manual handlers\n')
}
})
})
// Create client with REST helper
const dbHelper = createClient({
dbSpec,
adapter: (dbSpec) => new CustomAdapter(dbSpec, {
handlers: createRESTHandlers({
baseUrl: API_BASE,
formatFilter: (filter: FilterOp) => {
// JSONPlaceholder uses simple query params
if (filter.type === 'eq') {
return `${filter.column}=${filter.value}`
}
return ''
}
}),
onInit: async () => {
console.log('\nπ CustomAdapter initialized with REST helper\n')
}
})
})
// Test functions
async function testSelect() {
console.log('ββββββββββββββββββββββββββββββββββββββββ')
console.log('TEST 1: SELECT with filters and limit')
console.log('ββββββββββββββββββββββββββββββββββββββββ')
const { data, error } = await dbManual
.from('posts')
.eq('userId', 1)
.limit(3)
.select('id, title, userId')
if (error) {
console.error('β Error:', error.message)
} else {
console.log('β
Success! Found posts:', data)
}
console.log('')
}
async function testSelectWithOrdering() {
console.log('ββββββββββββββββββββββββββββββββββββββββ')
console.log('TEST 2: SELECT with ordering')
console.log('ββββββββββββββββββββββββββββββββββββββββ')
const { data, error } = await dbManual
.from('users')
.limit(3)
.order('name', { ascending: true })
.select('id, name, email')
if (error) {
console.error('β Error:', error.message)
} else {
console.log('β
Success! Found users:', data)
}
console.log('')
}
async function testSelectWithMultipleFilters() {
console.log('ββββββββββββββββββββββββββββββββββββββββ')
console.log('TEST 3: SELECT with multiple filters (client-side)')
console.log('ββββββββββββββββββββββββββββββββββββββββ')
const { data, error } = await dbManual
.from('posts')
.in('userId', [1, 2])
.limit(5)
.select('id, userId, title')
if (error) {
console.error('β Error:', error.message)
} else {
console.log('β
Success! Found posts:', data)
}
console.log('')
}
async function testInsert() {
console.log('ββββββββββββββββββββββββββββββββββββββββ')
console.log('TEST 4: INSERT')
console.log('ββββββββββββββββββββββββββββββββββββββββ')
const { data, error } = await dbManual
.from('posts')
.insert({
id: 101, // Include ID to satisfy schema validation
userId: 1,
title: 'Test Post from CustomAdapter',
body: 'This is a test post created using vibecode-db CustomAdapter!'
})
if (error) {
console.error('β Error:', error.message)
} else {
console.log('β
Success! Inserted post:', data)
}
console.log('')
}
async function testUpdate() {
console.log('ββββββββββββββββββββββββββββββββββββββββ')
console.log('TEST 5: UPDATE')
console.log('ββββββββββββββββββββββββββββββββββββββββ')
const { data, error } = await dbManual
.from('posts')
.eq('id', 1)
.update({ title: 'Updated Title via CustomAdapter' })
if (error) {
console.error('β Error:', error.message)
} else {
console.log('β
Success! Updated post:', data)
}
console.log('')
}
async function testDelete() {
console.log('ββββββββββββββββββββββββββββββββββββββββ')
console.log('TEST 6: DELETE')
console.log('ββββββββββββββββββββββββββββββββββββββββ')
const { data, error } = await dbManual
.from('posts')
.eq('id', 1)
.delete()
if (error) {
console.error('β Error:', error.message)
} else {
console.log('β
Success! Deleted post')
}
console.log('')
}
async function testRESTHelper() {
console.log('ββββββββββββββββββββββββββββββββββββββββ')
console.log('TEST 7: Using REST Helper')
console.log('ββββββββββββββββββββββββββββββββββββββββ')
const { data, error } = await dbHelper
.from('users')
.eq('id', 1)
.select('id, name, email, username')
if (error) {
console.error('β Error:', error.message)
} else {
console.log('β
Success! Found user:', data)
}
console.log('')
}
// Run all tests
async function runTests() {
console.log('\n')
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
console.log('β CustomAdapter Test Suite β')
console.log('β Testing with JSONPlaceholder API β')
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
console.log('\n')
try {
await testSelect()
await testSelectWithOrdering()
await testSelectWithMultipleFilters()
await testInsert()
await testUpdate()
await testDelete()
await testRESTHelper()
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
console.log('β β
All tests completed! β')
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
} catch (error) {
console.error('\nβ Test suite failed:', error)
}
}
// Run tests
runTests()