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

config.ts

64 lines1.8 KB

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