import { Application, Response } from 'express'; import { SynthOSConfig } from "../init"; import path from "path"; import { v4 } from "uuid"; import { clearCachedScripts } from '../scripts'; import { deleteSchema, isValidSchemaPayload, listTables, loadSchema, mergeSchema, newSchemaWrapper, saveSchema, updateSchemaWrapper, MergeMode, } from "./sharedTableSchema"; export function useDataRoutes(config: SynthOSConfig, app: Application): void { // Schema sidecar + table-list endpoints registered before the generic // table/record routes so the literal `_schema` / `_tables` segments // aren't captured by `:table` / `:table/:id`. app.get('/api/data/:page/_tables', (req, res) => handleListTables(config, req.params.page, res)); app.get('/api/data/:page/:table/_schema', (req, res) => handleGetSchema(config, req.params.page, req.params.table, res)); app.put('/api/data/:page/:table/_schema', (req, res) => handlePutSchema(config, req.params.page, req.params.table, req.query, req.body, res)); app.delete('/api/data/:page/:table/_schema', (req, res) => handleDeleteSchema(config, req.params.page, req.params.table, res)); app.get('/api/data/:page/:table', (req, res) => handleList(config, req.params.page, req.params.table, req.query, res)); app.get('/api/data/:page/:table/:id', (req, res) => handleGet(config, req.params.page, req.params.table, req.params.id, res)); app.post('/api/data/:page/:table', (req, res) => handleUpsert(config, req.params.page, req.params.table, req.body, res)); app.delete('/api/data/:page/:table/:id', (req, res) => handleDelete(config, req.params.page, req.params.table, req.params.id, res)); } // --------------------------------------------------------------------------- // Route handlers — records // --------------------------------------------------------------------------- async function handleList(config: SynthOSConfig, page: string, table: string, query: Record, res: Response): Promise { const sp = config.storageProvider; const folder = tableFolder(config, page, table); if (!(await sp.checkIfExists(folder))) { res.status(404).json({ error: 'table_not_found', page, table }); return; } const ids = (await sp.listFiles(folder)).filter(f => f.endsWith('.json')).map(f => f.replace('.json', '')); const rows: Record[] = []; for (const id of ids) { const file = recordFile(folder, id); try { const row = JSON.parse(await sp.loadFile(file)); row.id = id; rows.push(row); } catch (err: unknown) { console.error(err); } } // Paginate when limit is provided const limitParam = typeof query.limit === 'string' ? parseInt(query.limit, 10) : NaN; if (!isNaN(limitParam) && limitParam > 0) { const offset = Math.max(0, typeof query.offset === 'string' ? parseInt(query.offset, 10) || 0 : 0); const items = rows.slice(offset, offset + limitParam); res.json({ items, total: rows.length, offset, limit: limitParam, hasMore: offset + limitParam < rows.length }); } else { res.json(rows); } } async function handleGet(config: SynthOSConfig, page: string, table: string, id: string, res: Response): Promise { const sp = config.storageProvider; const folder = tableFolder(config, page, table); if (!(await sp.checkIfExists(folder))) { res.status(404).json({ error: 'table_not_found', page, table }); return; } const file = recordFile(folder, id); try { const row = JSON.parse(await sp.loadFile(file)); row.id = id; res.json(row); } catch (err: unknown) { res.json({}); } } async function handleUpsert(config: SynthOSConfig, page: string, table: string, body: any, res: Response): Promise { const sp = config.storageProvider; const id = body.id ?? v4(); const folder = tableFolder(config, page, table); const file = recordFile(folder, id); try { const row = { ...body, id }; await sp.ensureFolderExists(folder); await sp.saveFile(file, JSON.stringify(row, null, 4)); if (table === 'scripts') { clearCachedScripts(); } res.json(row); } catch (err: unknown) { console.error(err); res.status(500).send((err as Error).message); } } async function handleDelete(config: SynthOSConfig, page: string, table: string, id: string, res: Response): Promise { const sp = config.storageProvider; const folder = tableFolder(config, page, table); const file = recordFile(folder, id); try { if (await sp.checkIfExists(file)) { await sp.deleteFile(file); if (table === 'scripts') { clearCachedScripts(); } } res.json({ success: true }); } catch (err: unknown) { console.error(err); res.status(500).send((err as Error).message); } } // --------------------------------------------------------------------------- // Route handlers — schema sidecar // --------------------------------------------------------------------------- async function handleGetSchema(config: SynthOSConfig, page: string, table: string, res: Response): Promise { const wrapper = await loadSchema(config, pageNamespace(config, page), table); if (!wrapper) { res.status(404).json({ error: 'schema_not_found', page, table }); return; } res.json(wrapper); } async function handlePutSchema( config: SynthOSConfig, page: string, table: string, query: Record, body: any, res: Response, ): Promise { const incoming = body && typeof body === 'object' && body.schema ? body.schema : body; if (!isValidSchemaPayload(incoming)) { res.status(400).json({ error: 'invalid_schema', message: 'Body must be a JSON Schema object (or { schema: ... } wrapper).' }); return; } const merge: MergeMode = query.merge === 'replace' ? 'replace' : 'additive'; const definedBy = typeof body?.definedBy === 'string' ? body.definedBy : undefined; const namespace = pageNamespace(config, page); const existing = await loadSchema(config, namespace, table); const { merged, conflicts } = mergeSchema(existing?.schema, incoming, merge); if (conflicts.length > 0) { res.status(409).json({ error: 'schema_conflict', conflicts }); return; } const now = new Date().toISOString(); const wrapper = existing ? updateSchemaWrapper(existing, merged, now, definedBy) : newSchemaWrapper(merged, now, definedBy); await saveSchema(config, namespace, table, wrapper); res.json(wrapper); } async function handleDeleteSchema(config: SynthOSConfig, page: string, table: string, res: Response): Promise { await deleteSchema(config, pageNamespace(config, page), table); res.status(204).end(); } /** * Subfolders under `/pages//` that are NOT data tables. * `files` is the synthos.files namespace; it must not appear in the table list. */ const RESERVED_PAGE_SUBDIRS: ReadonlySet = new Set(['files']); async function handleListTables(config: SynthOSConfig, page: string, res: Response): Promise { const tables = await listTables(config, pageNamespace(config, page), RESERVED_PAGE_SUBDIRS); res.json({ tables }); } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function pageNamespace(config: SynthOSConfig, page: string): string { return path.join(config.pagesFolder, 'pages', page); } function tableFolder(config: SynthOSConfig, page: string, table: string): string { return path.join(pageNamespace(config, page), table); } function recordFile(folder: string, id: string): string { return path.join(folder, `${id}.json`); }