-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (42 loc) · 1.41 KB
/
server.js
File metadata and controls
51 lines (42 loc) · 1.41 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
import express from 'express';
import webpush from 'web-push';
import bodyParser from 'body-parser';
import cors from 'cors';
const app = express();
app.use(cors());
app.use(bodyParser.json());
// VAPID keys generated by web-push
const vapidKeys = {
publicKey: 'BMR5kcOL6Q4bl02dRNSPuvPElNQtyNRInvM47D6npe09WvvaQLBoaqDqRj7_TKPJmIsPUlllP3Rtfwl5iVwOlgY',
privateKey: 'j2AZPHkK-6HkJF6OtBWQJKIcNz0Rknqyj37zJEHQIGs'
};
webpush.setVapidDetails(
'mailto:your@email.com',
vapidKeys.publicKey,
vapidKeys.privateKey
);
// Store subscriptions in-memory for demo (use a DB in production)
const subscriptions = [];
app.post('/api/save-subscription', (req, res) => {
const subscription = req.body;
// Avoid duplicates
if (!subscriptions.find(sub => sub.endpoint === subscription.endpoint)) {
subscriptions.push(subscription);
}
res.status(201).json({ message: 'Subscription saved.' });
});
// Endpoint to trigger a push notification (for testing)
app.post('/api/send-reminder', async (req, res) => {
const { title, body } = req.body;
const notificationPayload = JSON.stringify({
title: title || 'Habit Reminder',
body: body || "It's time for your habit!"
});
const results = await Promise.all(subscriptions.map(sub =>
webpush.sendNotification(sub, notificationPayload).catch(err => err)
));
res.json({ results });
});
app.listen(4000, () => {
console.log('Push server running on port 4000');
});