File size: 2,085 Bytes
1646e50 | 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 | // 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}`);
}); |