From 3da365999d007eed549545ddd56693a2deba12b6 Mon Sep 17 00:00:00 2001 From: Naz Date: Thu, 5 Nov 2020 17:07:27 +1300 Subject: [PATCH] Added cron expression validation no issue - CRON format is the most common one used for job scheduling and is well known to most developers - This will become one of supported formats for job scheduling --- ghost/job-manager/lib/is-cron-expression.js | 32 +++++++++++++++++++ ghost/job-manager/package.json | 1 + .../test/is-cron-expression.test.js | 19 +++++++++++ 3 files changed, 52 insertions(+) create mode 100644 ghost/job-manager/lib/is-cron-expression.js create mode 100644 ghost/job-manager/test/is-cron-expression.test.js diff --git a/ghost/job-manager/lib/is-cron-expression.js b/ghost/job-manager/lib/is-cron-expression.js new file mode 100644 index 0000000000..ff7d6d79a8 --- /dev/null +++ b/ghost/job-manager/lib/is-cron-expression.js @@ -0,0 +1,32 @@ +const parser = require('cron-parser'); + +/** + * Checks if expression follows supported CRON format as follows + * e.g.: + * "2 * * * *" where: + * + * "* * * * * *" + * ┬ ┬ ┬ ┬ ┬ ┬ + * │ │ │ │ │ | + * │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun) + * │ │ │ │ └───── month (1 - 12) + * │ │ │ └────────── day of month (1 - 31) + * │ │ └─────────────── hour (0 - 23) + * │ └──────────────────── minute (0 - 59) + * └───────────────────────── second (0 - 59, optional) + * + * @param {String} expression in CRON format + * + * @returns {boolean} wheather or not the expression is valid + */ +const isCronExpression = (expression) => { + try { + parser.parseExpression(expression); + + return true; + } catch (err) { + return false; + } +}; + +module.exports = isCronExpression; diff --git a/ghost/job-manager/package.json b/ghost/job-manager/package.json index 9dce915326..cbe5027631 100644 --- a/ghost/job-manager/package.json +++ b/ghost/job-manager/package.json @@ -24,6 +24,7 @@ "sinon": "9.2.1" }, "dependencies": { + "cron-parser": "2.17.0", "fastq": "1.9.0", "p-wait-for": "3.1.0" } diff --git a/ghost/job-manager/test/is-cron-expression.test.js b/ghost/job-manager/test/is-cron-expression.test.js new file mode 100644 index 0000000000..08a467277d --- /dev/null +++ b/ghost/job-manager/test/is-cron-expression.test.js @@ -0,0 +1,19 @@ +// Switch these lines once there are useful utils +// const testUtils = require('./utils'); +require('./utils'); + +const isCronExpression = new require('../lib/is-cron-expression'); + +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(); + }); + + 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(); + }); +});