Open History to see the last commit
1import express from "express"
2import { sql } from "../db/postgres"
3import {
4 validateInsertConfig,
5 validateInsertTodo,
6 validateUpdateConfig,
7 validateUpdateTodo,
8} from "../db/validation"
9import { processMutations } from "./write-to-pg"
10import type { PendingMutation } from "../../../src/types"
11
12const router = express.Router()
13
14/**
15 * Process an array of PendingMutations, validate them, and write to the database
16 */
17router.post(`/api/mutations`, async (req, res) => {
18 try {
19 const pendingMutations: Array<PendingMutation> = req.body
20
21 if (!Array.isArray(pendingMutations)) {
22 return res.status(400).json({ error: `Expected an array of mutations` })
23 }
24
25 // Validate each mutation before processing
26 const validatedMutations = pendingMutations.map((mutation) => {
27 const relation = mutation.syncMetadata.relation as
28 | Array<string>
29 | undefined
30 const tableName = relation?.[1]
31 if (!tableName) {
32 throw new Error(`Could not find table name in relation metadata`)
33 }
34
35 const mutationCopy = { ...mutation }
36
37 // Validate based on operation type and table
38 switch (mutation.type) {
39 case `insert`: {
40 mutationCopy.modified =
41 tableName === `config`
42 ? validateInsertConfig(mutation.modified)
43 : validateInsertTodo(mutation.modified)
44 break
45 }
46 case `update`: {
47 mutationCopy.changes =
48 tableName === `config`
49 ? validateUpdateConfig(mutation.changes)
50 : validateUpdateTodo(mutation.changes)
51 break
52 }
53 case `delete`:
54 // No validation needed for deletes
55 break
56 default:
57 throw new Error(`Unknown operation type: ${mutation.type}`)
58 }
59
60 return mutationCopy
61 })
62
63 // Process the validated mutations
64 const txid = await processMutations(sql, validatedMutations)
65
66 // Return the transaction ID to the caller
67 return res.status(200).json({ txid })
68 } catch (error) {
69 console.error(`Error processing mutations:`, error)
70 return res.status(500).json({
71 error: `Failed to process mutations`,
72 details: error instanceof Error ? error.message : String(error),
73 })
74 }
75})
76
77export default router