-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
56 lines (45 loc) · 1.52 KB
/
server.js
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
const express = require("express");
const axios = require("axios");
const webpush = require("web-push");
const bodyParser = require("body-parser");
const app = express();
const PORT = process.env.PORT || 4000;
const serverKey =
"AAAAykKja5A:APA91bHJ0-jWbdBO0kcp5SUWS67cpAB5RW4lBeuG9UnJ_Rot3fsy01dqxqQMCI6VHvvKsRY_K2O_E3bixPUcuPRKVOs64-mIo2N3joDg9YN-hSVI4bBwiJ3Xg6nz4eEJdLACdGgm5zUT";
const privateKey = "3LlzvLO1khMPuW9QG-42FEuwr8mRcmgKxxF0SSlMbxI";
const publicKey =
"BOagsDf_-tNHQeP5OKqqw4mgw7LycsU3FODH8sQoJFhpIu63ZHIBf2E9meq3Rn6uWnDxRUMocJ5RHi2P1re4opI";
webpush.setVapidDetails("mailto:[email protected]", publicKey, privateKey);
app.use(express.static("public"));
app.use(bodyParser.json());
let randomNumber = 0;
let actionsReceived = 0;
const push = [];
app.get("/fact", (req, res) => {
axios
.get("https://catfact.ninja/fact")
.then(({ data: { fact } }) => res.json({ fact }))
.catch(err => res.json({ fact: `Error ${randomNumber++}` }));
});
app.post("/action", (req, res) => {
actionsReceived++;
res.status(200).json({ action: actionsReceived });
});
app.get("/action", (req, res) => {
res.status(200).json({ action: actionsReceived });
});
app.post("/subscribe", (req, res) => {
push.push(req.body.data);
res.status(200).send();
});
app.get("/send", (req, res) => {
res.status(200).send();
const notification = JSON.stringify({
title: "Cat Fact!",
body: "This is a test notification"
});
push.forEach(sub => {
webpush.sendNotification(sub, notification);
});
});
app.listen(PORT);