This repository has been archived by the owner on Jul 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScheduledMessageSchedulerService.js
executable file
·62 lines (51 loc) · 1.76 KB
/
ScheduledMessageSchedulerService.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
'use strict';
const _ = require('lodash');
const schedule = require('node-schedule');
const sendMessageTo = require('./utils/sendMessageTo');
let scheduledJobs = {};
const PlayerProvider = require('./controllers/db/PlayerProvider');
const playerProvider = new PlayerProvider();
const ScheduledMessageSchedulerService = function() {};
ScheduledMessageSchedulerService.prototype.scheduleMessage = function(scheduledMessage) {
const uuid = scheduledMessage.uuid;
if (scheduledJobs[uuid]) {
return;
}
if (_.trim(scheduledMessage.playerId).length === 0) {
// No playerId
return;
}
if (_.trim(scheduledMessage.message).length === 0) {
// No message
return;
}
console.log('Scheduling',uuid,'for',scheduledMessage.scheduledAt.toDate());
const scheduledJob = schedule.scheduleJob(scheduledMessage.scheduledAt.toDate(), function() {
playerProvider.getPlayerById(scheduledMessage.playerId).then(function(player) {
if (player === null) {
return;
}
if (_.isEmpty(player.phoneNumber)) {
return;
}
console.log('Sending message to', player.phoneNumber, 'message:', scheduledMessage.message);
sendMessageTo(player.phoneNumber, scheduledMessage.message).catch(function(err) {
console.error(err);
}).finally(function() {
delete scheduledMessage[uuid];
});
});
});
scheduledJobs[uuid] = scheduledJob;
};
ScheduledMessageSchedulerService.prototype.getScheduledJobByUuid = function(uuid) {
return scheduledJobs[uuid];
};
ScheduledMessageSchedulerService.prototype.cancelScheduledJobByUuid = function(uuid) {
let scheduledJob = scheduledJobs[uuid];
if (scheduledJob) {
schedule.cancelJob(scheduledJob);
}
};
const scheduledMessageSchedulerService = new ScheduledMessageSchedulerService();
module.exports = scheduledMessageSchedulerService;