pr_01m47d24b0e6n91zwymwxg0vpx/packages/contracts/src/result.ts
| 1 | /** |
| 2 | * Expected failures cross service boundaries as values, not exceptions: |
| 3 | * Worker RPC does not preserve error classes, and callers should have to |
| 4 | * handle them. |
| 5 | */ |
| 6 | export type FailureCode = |
| 7 | | "not_found" |
| 8 | | "forbidden" |
| 9 | | "unauthenticated" |
| 10 | | "conflict" |
| 11 | | "invalid"; |
| 12 | |
| 13 | export type Failure = { code: FailureCode; message: string }; |
| 14 | |
| 15 | export type Result<T> = { ok: true; value: T } | { ok: false; error: Failure }; |
| 16 | |
| 17 | export function ok<T>(value: T): Result<T> { |
| 18 | return { ok: true, value }; |
| 19 | } |
| 20 | |
| 21 | export function fail(code: FailureCode, message: string): Result<never> { |
| 22 | return { ok: false, error: { code, message } }; |
| 23 | } |
| 24 | |
| 25 | const HTTP_STATUS: Record<FailureCode, number> = { |
| 26 | not_found: 404, |
| 27 | forbidden: 403, |
| 28 | unauthenticated: 401, |
| 29 | conflict: 409, |
| 30 | invalid: 422, |
| 31 | }; |
| 32 | |
| 33 | export function httpStatus(failure: Failure): number { |
| 34 | return HTTP_STATUS[failure.code]; |
| 35 | } |
| 36 | |
| 37 | /** Returned when an account with an unconfirmed email tries to change something. */ |
| 38 | export const UNVERIFIED = fail( |
| 39 | "forbidden", |
| 40 | "Confirm your email address first. Check your inbox, or resend the link from the banner on g1t.sh.", |
| 41 | ); |