Skip to content

Commit

Permalink
feat(scripts): init cron ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
PierreBrisorgueil committed Apr 22, 2020
1 parent b58129e commit de1c7a1
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 2 deletions.
17 changes: 15 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"mongoose": "~5.9.10",
"morgan": "^1.10.0",
"multer": "~1.4.2",
"node-cron": "^2.0.3",
"nodemailer": "~6.4.6",
"nodemon": "^2.0.3",
"object-path": "^0.11.4",
Expand Down
58 changes: 58 additions & 0 deletions scripts/crons/apis.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const chalk = require('chalk');
const path = require('path');
const _ = require('lodash');
const cron = require('node-cron');
const mongoose = require('mongoose');

const config = require(path.resolve('./config'));
const mongooseService = require(path.resolve('./lib/services/mongoose'));
const mails = require(path.resolve('./lib/helpers/mails'));

const cronJobs = async () => {
try {
console.log(chalk.bold.green('Start CronJobs worker.'));

await mongooseService.connect();
await mongooseService.loadModels();
mongoose.set('debug', false);

const ScrapService = require(path.resolve('./modules/scraps/services/scraps.service'));
let scraps = await ScrapService.list();
scraps = _.remove(scraps, (scrap) => scrap.cron);
console.log(chalk.green(`Scraps cron list requested: ${scraps.length}`));

_.forEach(scraps, (_scrap) => {
if (cron.validate(_scrap.cron)) {
console.log(chalk.blue(`- Init ${_scrap.title} (${_scrap.id}) : ${_scrap.cron}`));

cron.schedule(_scrap.cron, async () => {
console.log(chalk.blue(`- Running ${_scrap.title} (${_scrap.id}) : ${_scrap.cron}`));

const scrap = await ScrapService.get(_scrap.id);
const load = await ScrapService.load(scrap);

if (load.result.type !== 'success' && load.scrap.alert && load.scrap.alert !== '') {
mails.sendMail({
template: 'scrap-failed-alert',
from: config.mailer.from,
to: load.scrap.alert,
subject: `Scrap Failed : ${load.scrap.title}`,
params: {
result: JSON.stringify(load.result, null, 2),
scrapTitle: load.scrap.title,
appName: config.app.title,
appContact: config.app.appContact,
},
});
}
});
}
});

console.log(chalk.green(`Scraps cron list Charged: ${scraps.length}`));
} catch (err) {
console.log(chalk.bold.red(`Error ${err}`));
}
};

cronJobs();

0 comments on commit de1c7a1

Please sign in to comment.