Files
tout-doux/resources/ts/lib/cron.ts
T
klemek a9b2e31d81
TS Lint / ESLint (push) Has been cancelled
TS Lint / Oxlint (push) Has been cancelled
TS Lint / TypeScript (push) Has been cancelled
refactor: format
2026-07-14 11:47:05 +02:00

73 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;
}
}