Open History to see the last commit
1import express from 'express'
2import cors from 'cors'
3import { sql } from '../db/postgres'
4import {
5 validateInsertConfig,
6 validateInsertTodo,
7 validateUpdateConfig,
8 validateUpdateTodo,
9} from '../db/validation'
10import type { Express } from 'express'
11import type { Txid } from '@tanstack/electric-db-collection'
12
13// Create Express app
14const app: Express = express()
15const PORT = process.env.PORT || 3001
16
17// Middleware
18app.use(cors())
19app.use(express.json())
20
21// Health check endpoint
22app.get(`/api/health`, (req, res) => {
23 res.status(200).json({ status: `ok` })
24})
25
26// Generate a transaction ID
27async function generateTxId(tx: any): Promise<Txid> {
28 // The ::xid cast strips off the epoch, giving you the raw 32-bit value
29 // that matches what PostgreSQL sends in logical replication streams
30 // (and then exposed through Electric which we'll match against
31 // in the client).
32 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
33 const txid = result[0]?.txid
34
35 if (txid === undefined) {
36 throw new Error(`Failed to get transaction ID`)
37 }
38
39 return parseInt(txid, 10)
40}
41
42// ===== TODOS API =====
43
44// GET all todos
45app.get(`/api/todos`, async (req, res) => {
46 try {
47 const todos = await sql`SELECT * FROM todos`
48 return res.status(200).json(todos)
49 } catch (error) {
50 console.error(`Error fetching todos:`, error)
51 return res.status(500).json({
52 error: `Failed to fetch todos`,
53 details: error instanceof Error ? error.message : String(error),
54 })
55 }
56})
57
58// GET a single todo by ID
59app.get(`/api/todos/:id`, async (req, res) => {
60 try {
61 const { id } = req.params
62 const [todo] = await sql`SELECT * FROM todos WHERE id = ${id}`
63
64 if (!todo) {
65 return res.status(404).json({ error: `Todo not found` })
66 }
67
68 return res.status(200).json(todo)
69 } catch (error) {
70 console.error(`Error fetching todo:`, error)
71 return res.status(500).json({
72 error: `Failed to fetch todo`,
73 details: error instanceof Error ? error.message : String(error),
74 })
75 }
76})
77
78// POST create a new todo
79app.post(`/api/todos`, async (req, res) => {
80 try {
81 const todoData = validateInsertTodo(req.body)
82
83 let txid!: Txid
84 const newTodo = await sql.begin(async (tx) => {
85 txid = await generateTxId(tx)
86
87 const [result] = await tx`
88 INSERT INTO todos ${tx(todoData)}
89 RETURNING *
90 `
91 return result
92 })
93
94 return res.status(201).json({ todo: newTodo, txid })
95 } catch (error) {
96 console.error(`Error creating todo:`, error)
97 return res.status(500).json({
98 error: `Failed to create todo`,
99 details: error instanceof Error ? error.message : String(error),
100 })
101 }
102})
103
104// PUT update a todo
105app.put(`/api/todos/:id`, async (req, res) => {
106 try {
107 const { id } = req.params
108 const todoData = validateUpdateTodo(req.body)
109
110 let txid!: Txid
111 const updatedTodo = await sql.begin(async (tx) => {
112 txid = await generateTxId(tx)
113
114 const [result] = await tx`
115 UPDATE todos
116 SET ${tx(todoData)}
117 WHERE id = ${id}
118 RETURNING *
119 `
120
121 if (!result) {
122 throw new Error(`Todo not found`)
123 }
124
125 return result
126 })
127
128 return res.status(200).json({ todo: updatedTodo, txid })
129 } catch (error) {
130 if (error instanceof Error && error.message === `Todo not found`) {
131 return res.status(404).json({ error: `Todo not found` })
132 }
133
134 console.error(`Error updating todo:`, error)
135 return res.status(500).json({
136 error: `Failed to update todo`,
137 details: error instanceof Error ? error.message : String(error),
138 })
139 }
140})
141
142// DELETE a todo
143app.delete(`/api/todos/:id`, async (req, res) => {
144 try {
145 const { id } = req.params
146
147 let txid!: Txid
148 await sql.begin(async (tx) => {
149 txid = await generateTxId(tx)
150
151 const [result] = await tx`
152 DELETE FROM todos
153 WHERE id = ${id}
154 RETURNING id
155 `
156
157 if (!result) {
158 throw new Error(`Todo not found`)
159 }
160 })
161
162 return res.status(200).json({ success: true, txid })
163 } catch (error) {
164 if (error instanceof Error && error.message === `Todo not found`) {
165 return res.status(404).json({ error: `Todo not found` })
166 }
167
168 console.error(`Error deleting todo:`, error)
169 return res.status(500).json({
170 error: `Failed to delete todo`,
171 details: error instanceof Error ? error.message : String(error),
172 })
173 }
174})
175
176// ===== CONFIG API =====
177
178// GET all config entries
179app.get(`/api/config`, async (req, res) => {
180 try {
181 const config = await sql`SELECT * FROM config`
182 return res.status(200).json(config)
183 } catch (error) {
184 console.error(`Error fetching config:`, error)
185 return res.status(500).json({
186 error: `Failed to fetch config`,
187 details: error instanceof Error ? error.message : String(error),
188 })
189 }
190})
191
192// GET a single config by ID
193app.get(`/api/config/:id`, async (req, res) => {
194 try {
195 const { id } = req.params
196 const [config] = await sql`SELECT * FROM config WHERE id = ${id}`
197
198 if (!config) {
199 return res.status(404).json({ error: `Config not found` })
200 }
201
202 return res.status(200).json(config)
203 } catch (error) {
204 console.error(`Error fetching config:`, error)
205 return res.status(500).json({
206 error: `Failed to fetch config`,
207 details: error instanceof Error ? error.message : String(error),
208 })
209 }
210})
211
212// POST create a new config
213app.post(`/api/config`, async (req, res) => {
214 try {
215 console.log(`POST /api/config`, req.body)
216 const configData = validateInsertConfig(req.body)
217
218 let txid!: Txid
219 const newConfig = await sql.begin(async (tx) => {
220 txid = await generateTxId(tx)
221
222 const [result] = await tx`
223 INSERT INTO config ${tx(configData)}
224 RETURNING *
225 `
226 return result
227 })
228
229 return res.status(201).json({ config: newConfig, txid })
230 } catch (error) {
231 console.error(`Error creating config:`, error)
232 return res.status(500).json({
233 error: `Failed to create config`,
234 details: error instanceof Error ? error.message : String(error),
235 })
236 }
237})
238
239// PUT update a config
240app.put(`/api/config/:id`, async (req, res) => {
241 try {
242 const { id } = req.params
243 const configData = validateUpdateConfig(req.body)
244
245 let txid!: Txid
246 const updatedConfig = await sql.begin(async (tx) => {
247 txid = await generateTxId(tx)
248
249 const [result] = await tx`
250 UPDATE config
251 SET ${tx(configData)}
252 WHERE id = ${id}
253 RETURNING *
254 `
255
256 if (!result) {
257 throw new Error(`Config not found`)
258 }
259
260 return result
261 })
262
263 return res.status(200).json({ config: updatedConfig, txid })
264 } catch (error) {
265 if (error instanceof Error && error.message === `Config not found`) {
266 return res.status(404).json({ error: `Config not found` })
267 }
268
269 console.error(`Error updating config:`, error)
270 return res.status(500).json({
271 error: `Failed to update config`,
272 details: error instanceof Error ? error.message : String(error),
273 })
274 }
275})
276
277// DELETE a config
278app.delete(`/api/config/:id`, async (req, res) => {
279 try {
280 const { id } = req.params
281
282 let txid!: Txid
283 await sql.begin(async (tx) => {
284 txid = await generateTxId(tx)
285
286 const [result] = await tx`
287 DELETE FROM config
288 WHERE id = ${id}
289 RETURNING id
290 `
291
292 if (!result) {
293 throw new Error(`Config not found`)
294 }
295 })
296
297 return res.status(200).json({ success: true, txid })
298 } catch (error) {
299 if (error instanceof Error && error.message === `Config not found`) {
300 return res.status(404).json({ error: `Config not found` })
301 }
302
303 console.error(`Error deleting config:`, error)
304 return res.status(500).json({
305 error: `Failed to delete config`,
306 details: error instanceof Error ? error.message : String(error),
307 })
308 }
309})
310
311// Start server
312app.listen(PORT, () => {
313 console.log(`Server running on port ${PORT}`)
314})
315
316export default app