-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
59 lines (50 loc) · 1.64 KB
/
app.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
'use strict';
/** IMPORTS */
import { app, errorHandler } from 'mu';
import fetch from 'node-fetch';
import main from './services/main';
import { CronJob } from 'cron';
/** ENV */
import { CRON_FREQUENCY } from './config';
let isTaskRunning = false; //TODO: later save as proper task in DB
/**
* Cron job that triggers on a timely basis.
*
* @param {string} cronFrequency
*/
new CronJob(CRON_FREQUENCY, function() {
console.log(`*************************************************************************`);
console.log(`*** Email delivery triggered by cron job at ${new Date().toISOString()} ***`);
console.log(`*************************************************************************`);
fetch('http://localhost/email-delivery/', {method: 'POST'});
}, null, true);
/**
* post route that will be called by CronJob. It will trigger the process of sending the emails.
* Calls the main function situated in the services folder
*/
app.post('/email-delivery/', async function(_, res, next) {
if(isTaskRunning) {
return res.status(409).send().end();
}
else {
try{
isTaskRunning = true;
await main(res);
return res.status(202).send().end();
}
catch(err){
console.log('ERROR: something went wrong while initiating the email delivery service.');
console.log(err);
return next(new Error(err));
}
finally {
isTaskRunning = false;
}
}
});
process.on('unhandledRejection', (reason, p) => {
// application specific logging, throwing an error, or other logic here
isTaskRunning = false;
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
app.use(errorHandler);