migration-utils.ts 1.4 KB

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