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

todos.ts

71 lines2.1 KB

1import { createFileRoute } from '@tanstack/solid-router'
2import { json } from '@tanstack/solid-start'
3import { sql } from '../../db/postgres'
4import { validateInsertTodo } from '../../db/validation'
5import type { Txid } from '@tanstack/electric-db-collection'
6​
7// Generate a transaction ID
8async function generateTxId(tx: any): Promise<Txid> {
9 // The ::xid cast strips off the epoch, giving you the raw 32-bit value
10 // that matches what PostgreSQL sends in logical replication streams
11 // (and then exposed through Electric which we'll match against
12 // in the client).
13 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
14 const txid = result[0]?.txid
15​
16 if (txid === undefined) {
17 throw new Error(`Failed to get transaction ID`)
18 }
19​
20 return parseInt(txid, 10)
22​
23export const Route = createFileRoute(`/api/todos`)({
24 server: {
25 handlers: {
26 GET: async ({ request: _request }) => {
27 try {
28 const todos = await sql`SELECT * FROM todos`
29 return json(todos)
30 } catch (error) {
31 console.error(`Error fetching todos:`, error)
32 return json(
33 {
34 error: `Failed to fetch todos`,
35 details: error instanceof Error ? error.message : String(error),
36 },
37 { status: 500 },
38 )
39 }
40 },
41 POST: async ({ request }) => {
42 try {
43 const body = await request.json()
44 const todoData = validateInsertTodo(body)
45​
46 let txid!: Txid
47 const newTodo = await sql.begin(async (tx) => {
48 txid = await generateTxId(tx)
49​
50 const [result] = await tx`
51 INSERT INTO todos ${tx(todoData)}
52 RETURNING *
53 `
54 return result
55 })
56​
57 return json({ todo: newTodo, txid }, { status: 201 })
58 } catch (error) {
59 console.error(`Error creating todo:`, error)
60 return json(
61 {
62 error: `Failed to create todo`,
63 details: error instanceof Error ? error.message : String(error),
64 },
65 { status: 500 },
66 )
67 }
68 },
69 },
70 },
71})