|
| 1 | +const express = require('express'); |
| 2 | +const cors = require('cors'); |
| 3 | +const fs = require('fs').promises; |
| 4 | +const path = require('path'); |
| 5 | + |
| 6 | +const app = express(); |
| 7 | +const PORT = 3000; |
| 8 | +const DATA_FILE = path.join(__dirname, 'data', 'responses.json'); |
| 9 | + |
| 10 | +app.use(cors()); |
| 11 | +app.use(express.json()); |
| 12 | + |
| 13 | +async function ensureDataFile() { |
| 14 | + try { |
| 15 | + await fs.mkdir(path.dirname(DATA_FILE), { recursive: true }); |
| 16 | + try { |
| 17 | + await fs.access(DATA_FILE); |
| 18 | + } catch { |
| 19 | + await fs.writeFile(DATA_FILE, JSON.stringify([])); |
| 20 | + } |
| 21 | + } catch (error) { |
| 22 | + console.error('Error creating data file:', error); |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +async function readResponses() { |
| 27 | + try { |
| 28 | + const data = await fs.readFile(DATA_FILE, 'utf8'); |
| 29 | + return JSON.parse(data); |
| 30 | + } catch (error) { |
| 31 | + console.error('Error reading responses:', error); |
| 32 | + return []; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +async function writeResponses(responses) { |
| 37 | + try { |
| 38 | + await fs.writeFile(DATA_FILE, JSON.stringify(responses, null, 2)); |
| 39 | + return true; |
| 40 | + } catch (error) { |
| 41 | + console.error('Error writing responses:', error); |
| 42 | + return false; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +app.get('/api/responses', async (req, res) => { |
| 47 | + const responses = await readResponses(); |
| 48 | + res.json(responses); |
| 49 | +}); |
| 50 | + |
| 51 | +app.post('/api/responses', async (req, res) => { |
| 52 | + const newResponse = { |
| 53 | + ...req.body, |
| 54 | + timestamp: new Date().toISOString() |
| 55 | + }; |
| 56 | + |
| 57 | + const responses = await readResponses(); |
| 58 | + responses.push(newResponse); |
| 59 | + |
| 60 | + const success = await writeResponses(responses); |
| 61 | + |
| 62 | + if (success) { |
| 63 | + res.status(201).json({ message: 'Response saved', response: newResponse }); |
| 64 | + } else { |
| 65 | + res.status(500).json({ error: 'Failed to save response' }); |
| 66 | + } |
| 67 | +}); |
| 68 | + |
| 69 | +app.get('/health', (req, res) => { |
| 70 | + res.json({ status: 'ok' }); |
| 71 | +}); |
| 72 | + |
| 73 | +ensureDataFile().then(() => { |
| 74 | + app.listen(PORT, '0.0.0.0', () => { |
| 75 | + console.log(`Survey API running on port ${PORT}`); |
| 76 | + }); |
| 77 | +}); |
0 commit comments