Open History to see the last commit
1import { createServerFileRoute } from "@tanstack/react-start/server"
2import { json } from "@tanstack/react-start"
3import { sql } from "../../db/postgres"
4import { validateUpdateConfig } 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 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
10 const txid = result[0]?.txid
11
12 if (txid === undefined) {
13 throw new Error(`Failed to get transaction ID`)
14 }
15
16 return parseInt(txid, 10)
17}
18
19export const ServerRoute = createServerFileRoute(`/api/config/$id`).methods({
20 GET: async ({ params }) => {
21 try {
22 const { id } = params
23 const [config] = await sql`SELECT * FROM config WHERE id = ${id}`
24
25 if (!config) {
26 return json({ error: `Config not found` }, { status: 404 })
27 }
28
29 return json(config)
30 } catch (error) {
31 console.error(`Error fetching config:`, error)
32 return json(
33 {
34 error: `Failed to fetch config`,
35 details: error instanceof Error ? error.message : String(error),
36 },
37 { status: 500 }
38 )
39 }
40 },
41 PUT: async ({ params, request }) => {
42 try {
43 const { id } = params
44 const body = await request.json()
45 const configData = validateUpdateConfig(body)
46
47 let txid!: Txid
48 const updatedConfig = await sql.begin(async (tx) => {
49 txid = await generateTxId(tx)
50
51 const [result] = await tx`
52 UPDATE config
53 SET ${tx(configData)}
54 WHERE id = ${id}
55 RETURNING *
56 `
57
58 if (!result) {
59 throw new Error(`Config not found`)
60 }
61
62 return result
63 })
64
65 return json({ config: updatedConfig, txid })
66 } catch (error) {
67 if (error instanceof Error && error.message === `Config not found`) {
68 return json({ error: `Config not found` }, { status: 404 })
69 }
70
71 console.error(`Error updating config:`, error)
72 return json(
73 {
74 error: `Failed to update config`,
75 details: error instanceof Error ? error.message : String(error),
76 },
77 { status: 500 }
78 )
79 }
80 },
81 DELETE: async ({ params }) => {
82 try {
83 const { id } = params
84
85 let txid!: Txid
86 await sql.begin(async (tx) => {
87 txid = await generateTxId(tx)
88
89 const [result] = await tx`
90 DELETE FROM config
91 WHERE id = ${id}
92 RETURNING id
93 `
94
95 if (!result) {
96 throw new Error(`Config not found`)
97 }
98 })
99
100 return json({ success: true, txid })
101 } catch (error) {
102 if (error instanceof Error && error.message === `Config not found`) {
103 return json({ error: `Config not found` }, { status: 404 })
104 }
105
106 console.error(`Error deleting config:`, error)
107 return json(
108 {
109 error: `Failed to delete config`,
110 details: error instanceof Error ? error.message : String(error),
111 },
112 { status: 500 }
113 )
114 }
115 },
116})