Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
78 lines (62 loc) · 2.08 KB
/
Copy pathindex.js
File metadata and controls
78 lines (62 loc) · 2.08 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const app = express();
const DATA_FILE = process.env.DATA_FILE || path.join(__dirname, 'notifications.json');
const VALID_TYPES = ['success', 'error', 'warning', 'info'];
const MISSING_FIELDS_ERROR =
'Missing required fields: message and type are required.';
app.use(cors());
app.use(express.json());
const readData = () => JSON.parse(fs.readFileSync(DATA_FILE, 'utf-8'));
const writeData = (data) => fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
const getValidationError = (payload) => {
if (!payload || typeof payload !== 'object') {
return MISSING_FIELDS_ERROR;
}
const { message, type } = payload;
if (!message || !type) {
return MISSING_FIELDS_ERROR;
}
if (!VALID_TYPES.includes(type)) {
return `Invalid type. Must be one of: ${VALID_TYPES.join(', ')}`;
}
return null;
};
const createNotification = ({ message, type }) => ({
id: Date.now(),
message,
type,
timestamp: new Date().toISOString(),
});
// POST - Add a notification
app.post('/api/notifications', (req, res) => {
const validationError = getValidationError(req.body);
if (validationError) {
return res.status(400).json({ error: validationError });
}
const { message, type } = req.body;
const data = readData();
const newNotification = createNotification({ message, type });
// Add to front so most recent is first
data.notifications.unshift(newNotification);
writeData(data);
res.status(200).json(newNotification);
});
// GET - Retrieve all notifications
app.get('/api/notifications', (req, res) => {
const data = readData();
res.status(200).json(data.notifications);
});
// DELETE - Clear all notifications
app.delete('/api/notifications', (req, res) => {
const data = readData();
data.notifications = [];
writeData(data);
res.status(200).json({ success: true, message: "All notifications cleared" });
});
if (require.main === module) {
app.listen(3002, () => console.log('Notification service running on port 3002'));
}
module.exports = app;