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

todos.ts

67 lines2.0 KB

1import { createServerFileRoute } from "@tanstack/solid-start/server"
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 ServerRoute = createServerFileRoute(`/api/todos`).methods({
24 GET: async ({ request: _request }) => {
25 try {
26 const todos = await sql`SELECT * FROM todos`
27 return json(todos)
28 } catch (error) {
29 console.error(`Error fetching todos:`, error)
30 return json(
31 {
32 error: `Failed to fetch todos`,
33 details: error instanceof Error ? error.message : String(error),
34 },
35 { status: 500 }
36 )
37 }
38 },
39 POST: async ({ request }) => {
40 try {
41 const body = await request.json()
42 const todoData = validateInsertTodo(body)
43​
44 let txid!: Txid
45 const newTodo = await sql.begin(async (tx) => {
46 txid = await generateTxId(tx)
47​
48 const [result] = await tx`
49 INSERT INTO todos ${tx(todoData)}
50 RETURNING *
51 `
52 return result
53 })
54​
55 return json({ todo: newTodo, txid }, { status: 201 })
56 } catch (error) {
57 console.error(`Error creating todo:`, error)
58 return json(
59 {
60 error: `Failed to create todo`,
61 details: error instanceof Error ? error.message : String(error),
62 },
63 { status: 500 }
64 )
65 }
66 },
67})