refactor: reduce responsability of individual parts

This commit is contained in:
2026-07-10 11:24:21 +02:00
parent f4425494f5
commit cb31d4e8af
7 changed files with 156 additions and 119 deletions
+66
View File
@@ -0,0 +1,66 @@
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;
}
}