cron-js-parser
Version:
Cron expression parser to human readable format from Expression as well as Individual values
112 lines (111 loc) • 3.54 kB
JavaScript
import cronstrueWithLocales from 'cronstrue/i18n';
import { QuartzParser } from '../abstracts';
import { cycle, at, startAtRepeatCycleEvery, startCycleInRange, onWeekDay } from '../../constants/logical';
class Parser extends QuartzParser {
getExpression(cronObj) {
let expr = "";
expr += this.seconds(cronObj.seconds);
expr += this.minutes(cronObj.minutes);
expr += this.hours(cronObj.hours);
expr += this.daysOfMonth(cronObj.daysOfMonth);
expr += this.months(cronObj.months);
expr += this.daysOfWeek(cronObj.daysOfWeek);
expr += this.years(cronObj.years);
return expr;
}
isValid(cronObj) {
return true;
}
commonLogic(cronObj) {
let expr = "";
if (cronObj.mode === cycle) {
expr = "* ";
}
else if (cronObj.mode === startAtRepeatCycleEvery) {
expr = `${cronObj.value.startAt}/${cronObj.value.every} `;
}
else if (cronObj.mode === startCycleInRange) {
expr = `${cronObj.value.from}-${cronObj.value.to} `;
}
else if (cronObj.mode === at) {
if (cronObj.value.length > 0) {
expr = `${cronObj.value.toString()} `;
}
else {
throw new Error("Specified mode is missing values");
}
}
else {
expr = "0 ";
}
return expr;
}
seconds(cronObj) {
return this.commonLogic(cronObj);
}
minutes(cronObj) {
return this.commonLogic(cronObj);
}
hours(cronObj) {
return this.commonLogic(cronObj);
}
daysOfMonth(cronObj) {
if (cronObj === undefined) {
return "? ";
}
return this.commonLogic(cronObj);
}
months(cronObj) {
return this.commonLogic(cronObj);
}
daysOfWeek(cronObj) {
if (cronObj === undefined) {
return "? ";
}
let expr = "";
if (cronObj.mode === startAtRepeatCycleEvery) {
expr = `${cronObj.value.startAt}/${cronObj.value.every} `;
}
else if (cronObj.mode === onWeekDay) {
if (cronObj.value.isLastWeek) {
expr = cronObj.value.dayIndex + "L ";
}
else {
expr = cronObj.value.dayIndex + "#" + cronObj.value.weekIndex + " ";
}
}
else if (cronObj.mode === startCycleInRange) {
expr = `${cronObj.value.from}-${cronObj.value.to} `;
}
else if (cronObj.mode === at) {
if (cronObj.value.length > 0) {
expr = `${cronObj.value.toString()} `;
}
else {
throw new Error("Specified mode is missing values");
}
}
return expr;
}
years(cronObj) {
if (cronObj !== undefined) {
return this.commonLogic(cronObj);
}
return "";
}
}
export const parseHumanReadable = (cronExpr, cronValues, language) => {
let expr = cronExpr;
if (!cronExpr) {
const parser = new Parser();
expr = parser.getExpression(cronValues);
}
return cronstrueWithLocales.toString(expr, {
verbose: true,
locale: language
});
};
export const parseCronExpression = (cronValues) => {
const parser = new Parser();
return parser.getExpression(cronValues);
};