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