0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-04-15 03:01:37 -05:00

Switched cron validation library to cron-validate

no issue

- Previous library was relyting on try/catch block to check if the expression is valid. Flow control through error catching is not considered a good practice and can effect performance (https://riptutorial.com/javascript/example/5297/avoid-try-catch-in-performance-critical-functions)
This commit is contained in:
Naz 2020-11-10 13:33:01 +13:00
parent ae4f35ddd8
commit 70b42e3a75
3 changed files with 11 additions and 12 deletions

View file

@ -1,7 +1,10 @@
const parser = require('cron-parser');
const cronValidate = require('cron-validate');
/**
* Checks if expression follows supported CRON format as follows
* Checks if expression follows supported crontab format
* reference: https://www.adminschoice.com/crontab-quick-reference
* builder: https://crontab.guru/
*
* e.g.:
* "2 * * * *" where:
*
@ -15,18 +18,14 @@ const parser = require('cron-parser');
* minute (0 - 59)
* second (0 - 59, optional)
*
* @param {String} expression in CRON format
* @param {String} expression in crontab format (https://www.gnu.org/software/mcron/manual/html_node/Crontab-file.html)
*
* @returns {boolean} wheather or not the expression is valid
*/
const isCronExpression = (expression) => {
try {
parser.parseExpression(expression);
let cronResult = cronValidate(expression);
return true;
} catch (err) {
return false;
}
return cronResult.isValid();
};
module.exports = isCronExpression;

View file

@ -25,7 +25,7 @@
},
"dependencies": {
"@breejs/later": "4.0.2",
"cron-parser": "2.17.0",
"cron-validate": "1.4.0",
"fastq": "1.9.0",
"p-wait-for": "3.1.0"
}

View file

@ -8,12 +8,12 @@ describe('Is cron expression', function () {
it('valid cron expressions', function () {
should(isCronExpression('* * * * *')).be.true();
should(isCronExpression('1 * * * *')).be.true();
should(isCronExpression('* * 12-15 * * *'), 'Range should be 0-23').be.true();
should(isCronExpression('* 13-23 * * *'), 'Range should be 0-23').be.true();
});
it('invalid cron expressions', function () {
should(isCronExpression('123 * * * *')).not.be.true();
should(isCronExpression('a * * * *')).not.be.true();
should(isCronExpression('* * 12-36 * * *'), 'Invalid range should be 0-23').not.be.true();
should(isCronExpression('* 13-24 * * *'), 'Invalid range should be 0-23').not.be.true();
});
});