-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotificationController.js
More file actions
91 lines (73 loc) · 2.65 KB
/
Copy pathnotificationController.js
File metadata and controls
91 lines (73 loc) · 2.65 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
79
80
81
82
83
84
85
86
87
88
89
90
91
const { v4: uuidv4 } = require('uuid');
const { db } = require('../config/firebase');
const createNotification = async (req, res) => {
try {
const userId = req.user.user_id;
const { message, trigger_time } = req.body;
const notificationId = uuidv4();
const notificationData = {
notification_id: notificationId,
user_id: userId,
message,
trigger_time,
delivered: false,
created_at: new Date().toISOString(),
};
await db.collection('notifications').doc(notificationId).set(notificationData);
res.status(201).json({
message: 'Notification created successfully',
notification: notificationData,
});
} catch (error) {
console.error('Create notification error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
const getNotifications = async (req, res) => {
try {
const userId = req.user.user_id;
const snapshot = await db.collection('notifications')
.where('user_id', '==', userId)
.orderBy('trigger_time', 'desc')
.get();
const notifications = [];
snapshot.forEach(doc => notifications.push(doc.data()));
res.json({ notifications });
} catch (error) {
console.error('Get notifications error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
const markDelivered = async (req, res) => {
try {
const userId = req.user.user_id;
const notificationId = req.params.id;
const notifRef = db.collection('notifications').doc(notificationId);
const notifDoc = await notifRef.get();
if (!notifDoc.exists || notifDoc.data().user_id !== userId) {
return res.status(404).json({ error: 'Notification not found.' });
}
await notifRef.update({ delivered: true });
res.json({ message: 'Notification marked as read' });
} catch (error) {
console.error('Mark notification error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
const deleteNotification = async (req, res) => {
try {
const userId = req.user.user_id;
const notificationId = req.params.id;
const notifRef = db.collection('notifications').doc(notificationId);
const notifDoc = await notifRef.get();
if (!notifDoc.exists || notifDoc.data().user_id !== userId) {
return res.status(404).json({ error: 'Notification not found.' });
}
await notifRef.delete();
res.json({ message: 'Notification deleted successfully' });
} catch (error) {
console.error('Delete notification error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
module.exports = { createNotification, getNotifications, markDelivered, deleteNotification };