Created
May 10, 2021 05:05
-
-
Save emanuelet/51c0423f3b7290b163c113f38720a1d8 to your computer and use it in GitHub Desktop.
Convert Cron expression to RRule string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const parser = require('cron-parser') | |
const { RRule } = require('rrule') | |
const logger = require('tracer').colorConsole() | |
const maps = { | |
dayofmonth: 'bymonthday', | |
dayofweek: 'byweekday', | |
} | |
module.exports = { | |
convert: function (expr, currentDate, endDate) { | |
try { | |
let interval = parser.parseExpression(expr, { | |
currentDate: new Date(currentDate), | |
endDate: new Date(endDate), | |
}) | |
// Does not support yet RRule.HOURLY and RRule.MINUTELY | |
let freq = | |
interval.fields.month.length === 12 && | |
interval.fields.dayOfMonth.length === 31 && | |
interval.fields.dayOfWeek.length === 8 | |
? 'DAILY' | |
: interval.fields.month.length === 12 && | |
interval.fields.dayOfWeek.length === 8 | |
? 'MONTHLY' | |
: interval.fields.dayOfMonth.length === 1 && | |
interval.fields.month.length === 1 | |
? 'YEARLY' | |
: 'WEEKLY' | |
let rule = new RRule({ | |
freq: RRule[freq], | |
...Object.keys(interval.fields).reduce(function (result, key) { | |
result[ | |
key.includes('day') ? maps[key.toLowerCase()] : `by${key}` | |
] = key.includes('day') | |
? interval.fields[key] - 1 | |
: interval.fields[key] | |
return result | |
}, {}), | |
dtstart: currentDate, | |
until: endDate, | |
}) | |
return rule.toString() | |
} catch (err) { | |
logger.error(err.message) | |
} | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment