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

config.$id.ts

120 lines3.3 KB

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