67 lines
1.9 KiB
TypeScript
67 lines
1.9 KiB
TypeScript
|
|
import { CronType } from "@/enums";
|
|
import {CronExpressionParser} from "cron-parser";
|
|
|
|
export function parseCron(cron: string | null): { type: CronType, value: number } {
|
|
let value: RegExpMatchArray | null;
|
|
if (cron === null) {
|
|
return {
|
|
type: CronType.ONE_TIME,
|
|
value: 0
|
|
}
|
|
} else if ((value = /^0 (\d+) \* \* \*$/i.exec(cron)) !== null) {
|
|
return {
|
|
type: CronType.EVERY_DAY,
|
|
value: parseInt(value[1] ?? '')
|
|
}
|
|
} else if ((value = /^0 0 \* \* (\d+)$/i.exec(cron)) !== null) {
|
|
return {
|
|
type: CronType.EVERY_WEEK,
|
|
value: parseInt(value[1] ?? '')
|
|
}
|
|
} else if ((value = /^0 0 (\d+) \* \*$/i.exec(cron)) !== null) {
|
|
return {
|
|
type: CronType.EVERY_MONTH,
|
|
value: parseInt(value[1] ?? '')
|
|
}
|
|
} else if ((value = /^0 0 1 (\d+) \*$/i.exec(cron)) !== null) {
|
|
return {
|
|
type: CronType.EVERY_YEAR,
|
|
value: parseInt(value[1] ?? '')
|
|
}
|
|
} else {
|
|
return {
|
|
type: CronType.SPECIFIC,
|
|
value: 0
|
|
}
|
|
}
|
|
}
|
|
|
|
export function getCron(type: CronType, value: number, fallback: string): string | null {
|
|
switch(type) {
|
|
case CronType.EVERY_DAY:
|
|
return `0 ${value.toFixed(0)} * * *`;
|
|
case CronType.EVERY_WEEK:
|
|
return `0 0 * * ${value.toFixed(0)}`
|
|
case CronType.EVERY_MONTH:
|
|
return `0 0 ${value.toFixed(0)} * *`;
|
|
case CronType.EVERY_YEAR:
|
|
return `0 0 1 ${value.toFixed(0)} *`;
|
|
case CronType.SPECIFIC:
|
|
if (validCron(fallback)) {
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
export function validCron(cron: string): boolean {
|
|
try {
|
|
CronExpressionParser.parse(cron);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|