File
Blob: src/worker/contracts/trusted.ts
| 1 | import { IsoDateTime, type IsoDateTime as IsoDateTimeValue } from "@/contracts/common"; |
| 2 | |
| 3 | type TrustedCodec<T> = { |
| 4 | is(value: unknown): value is T; |
| 5 | }; |
| 6 | |
| 7 | export const expectTrusted = <T>(codec: TrustedCodec<T>, value: unknown, label: string): T => { |
| 8 | if (!codec.is(value)) { |
| 9 | throw new Error(`Invalid trusted ${label}.`); |
| 10 | } |
| 11 | |
| 12 | return value; |
| 13 | }; |
| 14 | |
| 15 | export const nullableTrusted = <T>(codec: TrustedCodec<T>, value: unknown, label: string): T | null => |
| 16 | value === null ? null : expectTrusted(codec, value, label); |
| 17 | |
| 18 | export const isoDateTimeFromTimestamp = (value: number): IsoDateTimeValue => |
| 19 | expectTrusted(IsoDateTime, new Date(value).toISOString(), "IsoDateTime"); |
| 20 | |
| 21 | export const nullableIsoDateTimeFromTimestamp = (value: number | null): IsoDateTimeValue | null => |
| 22 | value === null ? null : isoDateTimeFromTimestamp(value); |