migration-utils.ts38 lines · main
1import dayjs, { Dayjs } from 'dayjs'
2
3/**
4 * Safely parses a migration version string as a date.
5 * Migration versions are typically in the format YYYYMMDDHHmmss (e.g., "20231128095400").
6 * However, some projects may have custom version formats (e.g., "001", "002") that cannot be parsed as dates.
7 *
8 * @param version - Migration version string
9 * @returns Dayjs object (UTC mode) if the version is a valid datetime, undefined otherwise
10 *
11 * @example
12 * const parsed = parseMigrationVersion('20231128095400')
13 * if (parsed) {
14 * console.log(parsed.fromNow()) // "2 hours ago"
15 * console.log(parsed.format('DD MMM YYYY')) // "28 Nov 2023"
16 * }
17 *
18 * @example
19 * const invalid = parseMigrationVersion('001') // returns undefined
20 */
21export function parseMigrationVersion(version: string | null | undefined): Dayjs | undefined {
22 if (!version) return undefined
23
24 // Must contain only digits
25 if (!/^\d{14}$/.test(version)) return undefined
26
27 const parsed = dayjs.utc(version, 'YYYYMMDDHHmmss', true)
28 return parsed.isValid() ? parsed : undefined
29}
30
31/**
32 * Formats a migration version string as a human-readable UTC date label.
33 * Returns 'Unknown' if the version cannot be parsed.
34 */
35export function formatMigrationVersionLabel(version: string | null | undefined): string {
36 const parsed = parseMigrationVersion(version)
37 return parsed ? parsed.format('DD MMM YYYY, HH:mm:ss') : 'Unknown'
38}