g1t/packages/contracts/src/result.ts

35 lines872 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Initial g1t: services, event bus, intents and attempts1/**
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 */
6export type FailureCode =
7 | "not_found"
8 | "forbidden"
9 | "unauthenticated"
10 | "conflict"
11 | "invalid";
12
13export type Failure = { code: FailureCode; message: string };
14
15export type Result<T> = { ok: true; value: T } | { ok: false; error: Failure };
16
17export function ok<T>(value: T): Result<T> {
18 return { ok: true, value };
19}
20
21export function fail(code: FailureCode, message: string): Result<never> {
22 return { ok: false, error: { code, message } };
23}
24
25const HTTP_STATUS: Record<FailureCode, number> = {
26 not_found: 404,
27 forbidden: 403,
28 unauthenticated: 401,
29 conflict: 409,
30 invalid: 422,
31};
32
33export function httpStatus(failure: Failure): number {
34 return HTTP_STATUS[failure.code];
35}