pr_01m47d15m3e54sn21z27rpy5n9/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 | /** The workspace has to pay before this can happen. */ |
| 13 | | "payment_required"; |
| 14 | |
| 15 | export type Failure = { code: FailureCode; message: string }; |
| 16 | |
| 17 | export type Result<T> = { ok: true; value: T } | { ok: false; error: Failure }; |
| 18 | |
| 19 | export function ok<T>(value: T): Result<T> { |
| 20 | return { ok: true, value }; |
| 21 | } |
| 22 | |
| 23 | export function fail(code: FailureCode, message: string): Result<never> { |
| 24 | return { ok: false, error: { code, message } }; |
| 25 | } |
| 26 | |
| 27 | const HTTP_STATUS: Record<FailureCode, number> = { |
| 28 | not_found: 404, |
| 29 | forbidden: 403, |
| 30 | unauthenticated: 401, |
| 31 | conflict: 409, |
| 32 | invalid: 422, |
| 33 | payment_required: 402, |
| 34 | }; |
| 35 | |
| 36 | export function httpStatus(failure: Failure): number { |
| 37 | return HTTP_STATUS[failure.code]; |
| 38 | } |
| 39 | |
| 40 | /** Returned when an account with an unconfirmed email tries to change something. */ |
| 41 | export const UNVERIFIED = fail( |
| 42 | "forbidden", |
| 43 | "Confirm your email address first. Check your inbox, or resend the link from the banner on g1t.sh.", |
| 44 | ); |