// server.js // --------------------------------------------------------------- // Minimal Express server that accepts POST /api/ingest, // validates a tiny bit, and appends the payload to ./records.json // --------------------------------------------------------------- import express from 'express'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const app = express(); const PORT = process.env.PORT ?? 3000; // ----- Middleware ----- app.use(express.json({ limit: '2mb' })); // body parser (JSON) app.use(express.static(__dirname)); // serve index.html & assets // ----- Helper ----- function safeAppend(recordArray) { const filePath = path.join(__dirname, 'records.json'); return fs.readFile(filePath, 'utf8') .catch(() => '[]') // file missing → start with empty array .then(data => { const existing = JSON.parse(data); const merged = existing.concat(recordArray); return fs.writeFile(filePath, JSON.stringify(merged, null, 2)); }); } // ----- Route ----- app.post('/api/ingest', async (req, res) => { const { sourceFile, format, records } = req.body; if (!Array.isArray(records) || !records.length) { return res.status(400).json({ error: 'Payload must contain a non‑empty records array' }); } // Very light sanity check (already validated client‑side) for (const rec of records) { if (!rec.name || !rec.email || !rec.phone) { return res.status(400).json({ error: 'Each record must contain name, email, and phone' }); } } try { await safeAppend(records); console.log(`[${new Date().toISOString()}] Received ${records.length} contacts from ${sourceFile} (${format})`); res.json({ status: 'ok', received: records.length }); } catch (e) { console.error('Write error:', e); res.status(500).json({ error: 'Failed to persist data' }); } }); // ----- Start ----- app.listen(PORT, () => { console.log(`🚀 Server listening at http://localhost:${PORT}`); });