| |
| |
| |
| |
| |
| 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; |
|
|
| |
| app.use(express.json({ limit: '2mb' })); |
| app.use(express.static(__dirname)); |
|
|
| |
| function safeAppend(recordArray) { |
| const filePath = path.join(__dirname, 'records.json'); |
| return fs.readFile(filePath, 'utf8') |
| .catch(() => '[]') |
| .then(data => { |
| const existing = JSON.parse(data); |
| const merged = existing.concat(recordArray); |
| return fs.writeFile(filePath, JSON.stringify(merged, null, 2)); |
| }); |
| } |
|
|
| |
| 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' }); |
| } |
|
|
| |
| 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' }); |
| } |
| }); |
|
|
| |
| app.listen(PORT, () => { |
| console.log(`🚀 Server listening at http://localhost:${PORT}`); |
| }); |