All files / src/endpoints setCronConfig.ts

100% Statements 28/28
92.85% Branches 13/14
100% Functions 7/7
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                3x   3x 3x 3x     3x 2x 1x       6x           4x 4x 1x   3x 11x       6x 6x   6x 1x 1x     5x 5x     6x 2x 2x     3x 3x   3x 3x    
import { Request, Response } from "express"
import pino from "pino"
 
import DynamicConfig, { VConfig } from "../modules/config/dynamic"
import { AutoImportJob } from "../queues/jobs/autoImport"
import { BaseJob } from "../queues/jobs/BaseJob"
import { BudgetSumUpJob } from "../queues/jobs/budgetSumUp"
 
const logger = pino()
 
enum CronType {
  AutoImport = "auto-import",
  BudgetSumUp = "budget-sum-up",
}
 
const cronConfig: Record<CronType, { key: VConfig; createJob: () => BaseJob }> = {
  [CronType.AutoImport]: { key: VConfig.AutoImportCron, createJob: () => new AutoImportJob() },
  [CronType.BudgetSumUp]: { key: VConfig.BudgetSumUpCron, createJob: () => new BudgetSumUpJob() },
}
 
function isCronType(value: string): value is CronType {
  return Object.values(CronType).includes(value as CronType)
}
 
// Accepts standard 5-field cron expressions as well as the 6-field variant that includes seconds.
// Each field may only contain digits and the cron operators (`*`, `/`, `,`, `-`).
function isValidCron(value: string): boolean {
  const fields = value.trim().split(/\s+/)
  if (fields.length !== 5 && fields.length !== 6) {
    return false
  }
  const fieldPattern = /^[\d*/,-]+$/
  return fields.every((field) => fieldPattern.test(field))
}
 
export async function setCronConfig(req: Request<{ type: string }, unknown, { cron?: string }>, res: Response) {
  const { type } = req.params
  logger.info("=================================== Setting cron config ===================================")
 
  if (!isCronType(type)) {
    logger.error("Invalid cron type %s", type)
    return res.status(400).send({ message: "Invalid cron type" })
  }
 
  const { key, createJob } = cronConfig[type]
  const cron = (req.body?.cron ?? "").trim()
 
  // An empty value clears the schedule.
  if (cron && !isValidCron(cron)) {
    logger.error("Invalid cron expression %s", cron)
    return res.status(400).send({ message: "Invalid cron expression" })
  }
 
  await DynamicConfig.set(key, cron)
  await createJob().rescheduleCronJob()
 
  logger.info("Cron config for %s set to '%s'", type, cron)
  return res.status(201).send({ type, cron })
}