File size: 1,468 Bytes
99df9a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const express = require('express');
const fs = require('fs');
const path = require('path');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

const dataDir = path.join(__dirname, 'data');
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });

const contactsFile = path.join(dataDir, 'contacts.json');
if (!fs.existsSync(contactsFile)) fs.writeFileSync(contactsFile, '[]');

app.get('/data/contacts', (req, res) => {
  try {
    const raw = fs.readFileSync(contactsFile, 'utf8');
    const json = JSON.parse(raw || '[]');
    res.json(json);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'failed to read contacts' });
  }
});

app.post('/data/contacts', (req, res) => {
  try {
    const body = req.body || {};
    const entry = {
      name: body.name || '',
      email: body.email || '',
      subject: body.subject || '',
      message: body.message || '',
      createdAt: new Date().toISOString(),
    };
    const raw = fs.readFileSync(contactsFile, 'utf8');
    const arr = JSON.parse(raw || '[]');
    arr.unshift(entry);
    fs.writeFileSync(contactsFile, JSON.stringify(arr, null, 2));
    res.status(201).json(entry);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'failed to save contact' });
  }
});

const port = process.env.PORT || 5173;
app.listen(port, () => console.log(`Data server listening on http://localhost:${port}`));