Skip to content
refs
30 lines · 1.3 KBRaw
1import type { Outcome, Problem } from "./contract/common.ts";
2import { refsErrorMessage, type RefsErrorCode } from "./contract/errors.ts";
3
4export function raise(code: RefsErrorCode, description: string): never {
5 throw new Error(refsErrorMessage(code, description));
6}
7
8export function ok(): Outcome;
9export function ok<T>(value: T): Outcome<T>;
10export function ok<T>(value?: T): Outcome<T | undefined> {
11 return { ok: true, value };
12}
13
14export 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
18export function invalid(message: string, field?: string): { ok: false; problem: Problem } {
19 return problem("invalid", message, field);
20}
21
22export 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. */
27export 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}