-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
92 lines (82 loc) · 2.78 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
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
92
const express = require('express');
const app = express();
require('dotenv').config();
app.set('port', process.env.PORT || 3001);
app.use(express.json());
const cors = require('cors');
app.use(cors());
// Web Push
const webpush = require('web-push');
webpush.setVapidDetails(
`mailto:${process.env.EMAIL}`,
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
// Knex
const environment = process.env.NODE_ENV || 'development';
const configuration = require('./knexfile')[environment];
const database = require('knex')(configuration);
// Endpoints
app.post('/subscriptions', (request, response) => {
const { uid, subscription } = request.body;
// Check if google auth uid exists
database('subscriptions').where({ google_auth_uid: uid })
.then(function(subscriptions) {
// If the uid exists, replace the subscrption object
if (subscriptions.length) {
database('subscriptions')
.where({ google_auth_uid: uid })
.update('subscription', JSON.stringify(subscription))
.then(function() {
return response.status(200).json({message: 'Subscription updated'});
})
.catch(function(err) {
return response.status(500).json({ err });
});
} else {
database('subscriptions')
.insert({google_auth_uid: uid, subscription})
.then(function(subscription) {
return response.status(201).json({message: 'New subscription created'})
})
.catch(function(err) {
return response.status(500).json({ err });
});
}
})
.catch(function(err) {
return response.status(500).json({ err });
})
});
app.post('/sendapush', (request, response) => {
const { uid } = request.body;
database('subscriptions')
.where({google_auth_uid: uid})
.then(function(user) {
if (user.length) {
const subscription = JSON.parse(user[0].subscription);
return sendPush(request, response, subscription);
} else {
return response.status(404).json({ error: `Could not find subscription with uid: ${uid}`});
}
})
.catch(function(err) {
return response.status(500).json({ err });
});
});
function sendPush(request, response, subscription) {
webpush.sendNotification(subscription, 'A reminder that you aren\'t going to live forever.')
.then(function(serviceResponse) {
if (serviceResponse.statusCode === 201) {
return response.status(200).json({ serviceResponse });
} else {
return response.status(500).json({ serviceResponse });
}
})
.catch(function(err) {
return response.status(500).json({ err });
});
}
app.listen(app.get('port'), () => {
console.log(`Practice web push server running on http://localhost:${app.get('port')}`);
});