-
Notifications
You must be signed in to change notification settings - Fork 1
/
twilio.js
100 lines (81 loc) · 2.39 KB
/
twilio.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
93
94
95
96
97
98
99
100
const camelCase = require('camelcase');
const Twilio = require('twilio');
const config = require('./config');
const { TIME } = require('./constants');
let lastRequestTime = Date.now();
// Convert keys to camelCase to conform with the twilio-node api definition contract
function camelCaseKeys(hashmap) {
const newhashmap = {};
Object.keys(hashmap).forEach(key => {
const newkey = camelCase(key);
newhashmap[newkey] = hashmap[key];
});
return newhashmap;
};
/**
* Create a device binding from a POST HTTP request
*
* @param {Object} binding
*
* @return {Promise}
* {Object.status}
* {Object.data}
* {Object.message}
*/
exports.registerBind = function registerBind(binding) {
const service = getTwilioClient();
return service.bindings.create(camelCaseKeys(binding)).then(binding => {
console.log(binding);
// Send a JSON response indicating success
return {
status: 200,
data: {message: 'Binding created!'},
};
}).catch(error => {
console.log(error);
return {
status: 500,
data: {
error: error,
message: `Failed to create binding: ${error}`,
},
};
});
};
// Notify - send a notification from a POST HTTP request
exports.sendNotification = function sendNotification(notification, bypass = false) {
const timeSinceLastRequest = Date.now() - lastRequestTime;
if (timeSinceLastRequest > 2 * TIME.HOUR && timeSinceLastRequest < 7 * TIME.HOUR && !bypass) return;
// Create a reference to the user notification service
const service = getTwilioClient();
// Send a notification
return service.notifications.create(camelCaseKeys({ body: notification, tag: 'all' })).then(message => {
console.log(message);
return {
status: 200,
data: {message: 'Successful sending notification'},
};
}).catch((error) => {
console.log(error);
return {
status: 500,
data: {error: error},
};
});
};
function getTwilioClient() {
// Twilio Library
const client = new Twilio(
config.TWILIO_API_KEY,
config.TWILIO_API_SECRET,
{ accountSid: config.TWILIO_ACCOUNT_SID }
);
// Get a reference to the user notification service instance
const service = client.notify.services(
config.TWILIO_NOTIFICATION_SERVICE_SID
);
return service;
}
exports.setLastRequestTime = function setLastRequestTime(time) {
lastRequestTime = time;
}