30 lines · 1.3 KBRaw
| 1 | import type { Outcome, Problem } from "./contract/common.ts"; |
| 2 | import { refsErrorMessage, type RefsErrorCode } from "./contract/errors.ts"; |
| 3 | |
| 4 | export function raise(code: RefsErrorCode, description: string): never { |
| 5 | throw new Error(refsErrorMessage(code, description)); |
| 6 | } |
| 7 | |
| 8 | export function ok(): Outcome; |
| 9 | export function ok<T>(value: T): Outcome<T>; |
| 10 | export function ok<T>(value?: T): Outcome<T | undefined> { |
| 11 | return { ok: true, value }; |
| 12 | } |
| 13 | |
| 14 | export function problem(code: Problem["code"], message: string, field?: string): { ok: false; problem: Problem } { |
| 15 | return { ok: false, problem: field ? { code, message, field } : { code, message } }; |
| 16 | } |
| 17 | |
| 18 | export function invalid(message: string, field?: string): { ok: false; problem: Problem } { |
| 19 | return problem("invalid", message, field); |
| 20 | } |
| 21 | |
| 22 | export function conflict(message: string, field?: string): { ok: false; problem: Problem } { |
| 23 | return problem("conflict", message, field); |
| 24 | } |
| 25 | |
| 26 | /** The first failed check as an `invalid` outcome on its field, or null when every check passed. Each check runs once. */ |
| 27 | export function firstInvalid(checks: Readonly<Record<string, string | undefined>>): { ok: false; problem: Problem } | null { |
| 28 | const failed = Object.entries(checks).find(([, message]) => message !== undefined); |
| 29 | return failed ? invalid(failed[1]!, failed[0]) : null; |
| 30 | } |