Recipes
Composition patterns — point-free pipelines, generator do-notation, and the Railway builder.
onrails gives you several ways to compose fallible steps. Reach for the simplest one that fits; escalate only when the shape demands it.
| Tier | Use case | Pattern |
|---|---|---|
| 1 | 1–2 steps, linear | direct data-first calls |
| 2 | 3+ steps, linear | pipe / flow (point-free) |
| 3 | branchy, a value reused across steps | tryGen generator |
| 4 | 4+ named steps, mixed sync/async IO | Railway builder |
Tip
Hover any token in the snippets below to see its inferred type — inference is the whole point.
import * as from "@onrails/result";
const = .(42);
const doubled = .(, () => * 2);Point-free composition (pipe / flow)
For linear pipelines, use the curried (data-last) form of each transform. Import
the package as a namespace so the names never collide with match from
ts-pattern or your own helpers.
import * as from "@onrails/result";
// pipe — thread a starting value through the steps
const = .(
(), // Result<Config, ParseError>
.(() => .),
.(() => ( ? .() : .({ : "empty" }))),
);
// flow — define a reusable point-free function (no value yet)
const = .(
,
.(() => .),
.(() => ( ? .() : .({ : "empty" }))),
);
(raw);pipe takes the value first; flow is the same composition with the value
deferred — ideal for building a parser factory once and reusing it.
Generator do-notation (tryGen / $)
When later steps depend on earlier values (and you'd otherwise nest flatMaps),
tryGen reads like straight-line code. $ unwraps an Ok or short-circuits the
whole block with its Err — onrails' answer to Rust's ?.
import { , , , , type } from "@onrails/result";
type = | | { : "inactive" };
// Annotate the return: `$` short-circuits by throwing, so its error types are
// NOT inferred — declare the full union yourself.
const : <{ : number; : string }, > = (() => {
const = (()); // unwrap, or short-circuit with CartError
const = (()); // unwrap, or short-circuit with UserError
if (!.) return ({ : "inactive" });
return ({ : .., : . });
});tryGen only infers the errors you return err(...) explicitly; the $
short-circuits are thrown, so they never reach the inferred type. Annotate the
result with the full union (as above) to keep the error channel honest.
The Railway builder
For named, multi-step workflows that mix sync and async IO, Railway threads a
growing context object through each step. Errors accumulate into one union; each
step sees the keys added before it.
import { } from "@onrails/result/railway";
const = .("id", () => .(), )
.("row", ({ }) => ..(), )
.("profile", "row", ({ }) => ({ : "not_found" as , }))
.("greeting", ({ }) => `Hi ${.}`)
.select(({ }) => );fromSync/fromPromiseadd a step (mapping a throw/rejection via the error fn).requireturns a nullable context value into a non-null one or a typed failure.deriveadds a pure value computed from the context.selectcollapses the final context into your result.
@onrails/result/fluent(fluent(r)) is app-edge sugar for dot-chaining — keep it out of library and service internals.ResultAsyncis already fluent, so there's nofluentAsyncwrapper. The wrapper is a bracket, not a value: open withfluent(...), close with a terminal (toResult/match/unwrapOr/…) in the same expression — see Core concepts.
Validating with Zod
A Zod schema's .parse throws on invalid input, so lift it once with
fromThrowable to get a Result-returning parser — or use safeParse if you'd rather not throw:
import { , , } from "@onrails/result";
import { } from "zod";
const = .({ : .(), : .().() });
type = .<typeof >;
type = { : "invalid"; : string[] };
const = (: unknown): => ({
: "invalid",
: instanceof . ? ..(() => .) : [()],
});
// throwing .parse -> Result
const = ((: unknown) => .(), );
// or non-throwing, via safeParse
const = (: unknown) => {
const = .();
return . ? (.) : ((.));
};Because a Zod schema's .parse is just a throwing function, it drops straight
into a Railway.fromSync starter — no adapter needed:
import { } from "@onrails/result/railway";
.("input", () => .(), ); // the first step of a workflowQuerying with Drizzle
Drizzle queries are promises, so wrap them with tryAsync. findFirst resolves
to undefined when there is no row — model that with Maybe, then cross back
into the error channel where absence is a real failure:
import { } from "@onrails/maybe";
import { } from "@onrails/maybe/interop";
import { } from "@onrails/result";
import { } from "drizzle-orm";
type = { : "db"; : unknown };
type = { : "not_found"; : string };
const = (: string) =>
(
...({ : (., ) }),
(): => ({ : "db", }),
); // ResultAsync<User | undefined, DbError>
const = (: string) =>
().(() =>
((), (): => ({ : "not_found", })),
);
// ResultAsync<User, DbError | NotFound>Mutations compose the same way — wrap insert(...).returning() and pick the row:
import { } from "@onrails/result";
const = (: ) =>
(
.().().(),
(): => ({ : "db", }),
).(() => [0]); // ResultAsync<User, DbError>Putting it together
A realistic checkout: a Railway that parses input, pulls a Maybe value
across the boundary with toResult, runs async IO, and accumulates a single
tagged-error union — then @onrails/pattern matches every variant
exhaustively into an HTTP response.
import { } from "@onrails/maybe";
import { } from "@onrails/maybe/interop";
import { } from "@onrails/pattern";
import * as from "@onrails/result";
import { } from "@onrails/result/railway";
type =
| { : "parse"; : string }
| { : "no_cart"; : string }
| { : "empty_cart" }
| { : "out_of_stock"; : string }
| { : "payment"; : string };
const = (: string) =>
.(
"userId",
() => .(),
(): => ({ : "parse", : () }),
)
// a Maybe crosses into the railway as a tagged failure
.("cart", ({ }) =>
((.()), (): => ({ : "no_cart", })),
)
.("filled", ({ }) =>
.. > 0 ? .() : .<, >({ : "empty_cart" }),
)
.(
"reservation",
({ }) => (),
(): => ({ : "out_of_stock", : () }),
)
.(
"receipt",
({ }) => (.),
(): => ({ : "payment", : () }),
)
.(({ }) => ({ : . }));
// ResultAsync<{ orderId: string }, CheckoutError>
// Result's own match forks Ok/Err; @onrails/pattern matches the error variants.
const = async (: string) =>
.(
await (),
() => ({ : 200, : `order ${.}` }),
() =>
()
.({ : "parse" }, () => ({ : 400, : . }))
.({ : "no_cart" }, () => ({ : 404, : "No cart" }))
.({ : "empty_cart" }, () => ({ : 422, : "Cart is empty" }))
.({ : "out_of_stock" }, () => ({ : 409, : . }))
.({ : "payment" }, () => ({ : 402, : . }))
.(),
);One workflow, three packages: Railway sequences the steps, Maybe models the
missing cart, and @onrails/pattern guarantees every failure is handled.