@tmlmobilidade/types
Version:
This package provides shared Zod validation schemas and their corresponding TypeScript types for use across projects. All types are automatically inferred from the schemas to ensure full type safety and reduce maintenance overhead.
23 lines (22 loc) • 969 B
JavaScript
/* * */
import { DateTime } from 'luxon';
import { z } from 'zod';
export const unixTimeStampSchema = z
.number()
.transform(validateUnixTimestamp)
.brand('UnixTimestamp');
/**
* This function validates if a number is a valid Unix Timestamp, in milliseconds.
* It is assumed the number will always be greater than 10^10 (1e10) to ensure it is in milliseconds.
* Throws an error if the date is invalid.
* @param milliseconds - The number to be validated.
* @returns The given number as a UnixTimestamp.
*/
export function validateUnixTimestamp(milliseconds) {
if (milliseconds < 1e10)
throw new Error(`Invalid value '${milliseconds}', expected a number in milliseconds but received a number smaller than 1e10`);
const parsedDate = DateTime.fromMillis(milliseconds);
if (!parsedDate.isValid)
throw new Error(`Invalid date '${milliseconds}, explanation: ${parsedDate.invalidExplanation}`);
return parsedDate.toMillis();
}