Skip to content

Commit

Permalink
improvement: type-safe values for time units
Browse files Browse the repository at this point in the history
  • Loading branch information
vvagaytsev committed May 14, 2024
1 parent 3aa1661 commit ef87fee
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions core/src/template-string/date-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import type { TemplateHelperFunction } from "./functions.js"
import { joi } from "../config/common.js"
import { format as formatFns, add } from "date-fns"

const validTimeUnits = ["years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"] as const
type TimeUnit = typeof validTimeUnits[number]

export const dateHelperFunctionSpecs: TemplateHelperFunction[] = [
{
name: "formatDate",
Expand Down Expand Up @@ -38,7 +41,7 @@ export const dateHelperFunctionSpecs: TemplateHelperFunction[] = [
amount: joi.number().required().description("The amount to modify or set the date by."),
unit: joi
.string()
.valid("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
.valid(...validTimeUnits)
.required()
.description("The unit to modify or set."),
mode: joi.string().valid("add", "set").description("Mode to either add or set the unit.").default("add"),
Expand All @@ -49,7 +52,7 @@ export const dateHelperFunctionSpecs: TemplateHelperFunction[] = [
{ input: ["2021-01-01T00:00:00Z", -1, "days", "add"], output: "2020-12-31T00:00:00.000Z" },
{ input: ["2021-01-01T00:00:00Z", 30, "seconds", "set"], output: "2021-01-01T00:00:30.000Z" },
],
fn: (date: string, amount: number, unit: string, mode: string) => {
fn: (date: string, amount: number, unit: TimeUnit, mode: string) => {
const dateClone = new Date(date)
switch (mode) {
case "add":
Expand Down Expand Up @@ -78,7 +81,7 @@ export const dateHelperFunctionSpecs: TemplateHelperFunction[] = [
dateClone.setMilliseconds(amount)
break
default:
throw new Error("Invalid unit")
return unit satisfies never
}
return dateClone.toISOString()
default:
Expand Down

0 comments on commit ef87fee

Please sign in to comment.