@railway-ts/pipelines 0.1.19 → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/API.md +1439 -0
- package/docs/GETTING_STARTED.md +301 -0
- package/docs/RECIPES.md +890 -0
- package/package.json +2 -1
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# Getting Started
|
|
2
|
+
|
|
3
|
+
A guided walkthrough. Each section introduces one concept, building to a complete pipeline by the end.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Step 1: Result -- Success or Failure
|
|
8
|
+
|
|
9
|
+
Every function that can fail returns a `Result` -- either `Ok` with a value, or `Err` with an error. No exceptions, no special return conventions, just data.
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { ok, err, isOk, isErr } from '@railway-ts/pipelines/result';
|
|
13
|
+
|
|
14
|
+
const divide = (a: number, b: number) => (b === 0 ? err('Cannot divide by zero') : ok(a / b));
|
|
15
|
+
|
|
16
|
+
const result = divide(10, 2);
|
|
17
|
+
|
|
18
|
+
if (isOk(result)) {
|
|
19
|
+
console.log(result.value); // 5
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (isErr(result)) {
|
|
23
|
+
console.error(result.error);
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
This is the fundamental building block. Functions don't throw -- they return a value that tells you what happened.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Step 2: map and flatMap -- Transform Without Unwrapping
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
const result = divide(10, 2);
|
|
35
|
+
if (isOk(result)) {
|
|
36
|
+
const doubled = result.value * 2;
|
|
37
|
+
// ... now what? wrap it again?
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`map` transforms the value inside an `Ok` without unwrapping it. If the `Result` is an `Err`, the transformation is skipped entirely:
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
import { ok, err, map } from '@railway-ts/pipelines/result';
|
|
45
|
+
|
|
46
|
+
const doubled = map(ok(5), (x) => x * 2);
|
|
47
|
+
// Ok(10)
|
|
48
|
+
|
|
49
|
+
const failed = map(err('nope'), (x) => x * 2);
|
|
50
|
+
// Err('nope') -- transformation skipped, error passed through
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`flatMap` is similar, but for transformations that themselves return a `Result`. This is how you chain operations where each step can fail:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import { ok, err, flatMap } from '@railway-ts/pipelines/result';
|
|
57
|
+
|
|
58
|
+
const divide = (a: number, b: number) => (b === 0 ? err('div by zero') : ok(a / b));
|
|
59
|
+
|
|
60
|
+
const result = flatMap(ok(10), (x) => divide(x, 2));
|
|
61
|
+
// Ok(5)
|
|
62
|
+
|
|
63
|
+
const result2 = flatMap(ok(10), (x) => divide(x, 0));
|
|
64
|
+
// Err('div by zero')
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The error propagates automatically. No if-checks, no try-catch.
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Step 3: pipe -- Build a Pipeline
|
|
72
|
+
|
|
73
|
+
Nesting `map` and `flatMap` calls gets awkward fast:
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
// This gets hard to read
|
|
77
|
+
const result = map(
|
|
78
|
+
flatMap(
|
|
79
|
+
map(ok(10), (x) => x + 1),
|
|
80
|
+
(x) => divide(x, 3),
|
|
81
|
+
),
|
|
82
|
+
(x) => x * 2,
|
|
83
|
+
);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`pipe` lets you write the same thing as a top-to-bottom flow. Each step receives the output of the previous step:
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
import { pipe } from '@railway-ts/pipelines/composition';
|
|
90
|
+
import { ok, mapWith, flatMapWith } from '@railway-ts/pipelines/result';
|
|
91
|
+
|
|
92
|
+
const divide = (a: number, b: number) => (b === 0 ? err('div by zero') : ok(a / b));
|
|
93
|
+
|
|
94
|
+
const result = pipe(
|
|
95
|
+
ok(10),
|
|
96
|
+
mapWith((x) => x + 1), // Ok(11)
|
|
97
|
+
flatMapWith((x) => divide(x, 3)), // Ok(3.666...)
|
|
98
|
+
mapWith((x) => x * 2), // Ok(7.333...)
|
|
99
|
+
);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The `With` suffix (`mapWith`, `flatMapWith`) means "curried" -- the function takes the transformation first and returns a function that takes the `Result`. This is what makes them composable inside `pipe`.
|
|
103
|
+
|
|
104
|
+
If any step produces an `Err`, everything after it is skipped:
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
const result = pipe(
|
|
108
|
+
ok(10),
|
|
109
|
+
mapWith((x) => x + 1), // Ok(11)
|
|
110
|
+
flatMapWith((x) => divide(x, 0)), // Err('div by zero')
|
|
111
|
+
mapWith((x) => x * 2), // skipped
|
|
112
|
+
mapWith((x) => x + 100), // skipped
|
|
113
|
+
);
|
|
114
|
+
// Err('div by zero')
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
> The `With` suffix pattern you've been using is called **point-free composition** -- see [Recipes: Point-Free Composition](RECIPES.md#point-free-composition) for more advanced uses like `flow` + point-free pipelines.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## Step 4: match -- Handle Both Cases
|
|
122
|
+
|
|
123
|
+
At the end of a pipeline, you need to do something with the result. `match` forces you to handle both `Ok` and `Err` -- TypeScript won't let you forget a branch:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { pipe } from '@railway-ts/pipelines/composition';
|
|
127
|
+
import { ok, mapWith, flatMapWith, match } from '@railway-ts/pipelines/result';
|
|
128
|
+
|
|
129
|
+
const result = pipe(
|
|
130
|
+
ok(10),
|
|
131
|
+
mapWith((x) => x + 1),
|
|
132
|
+
flatMapWith((x) => divide(x, 3)),
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
match(result, {
|
|
136
|
+
ok: (value) => console.log(`Result: ${value}`),
|
|
137
|
+
err: (error) => console.error(`Error: ${error}`),
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
That's the core pattern: build a pipeline with `pipe`, transform with `map`/`flatMap`, branch once at the end with `match`.
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## Step 5: Option -- Handle Missing Values
|
|
146
|
+
|
|
147
|
+
`Result` handles success vs. failure. `Option` handles presence vs. absence -- a value that may or may not exist. `Some` holds a value, `None` means nothing is there. The same `map`/`pipe`/`match` patterns you already know apply here.
|
|
148
|
+
|
|
149
|
+
The most common entry point is `fromNullable`, which wraps a value that might be `null` or `undefined`:
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
import { pipe } from '@railway-ts/pipelines/composition';
|
|
153
|
+
import { fromNullable, mapWith, filterWith, match } from '@railway-ts/pipelines/option';
|
|
154
|
+
|
|
155
|
+
const users = {
|
|
156
|
+
u1: { name: 'Alice', age: 30 },
|
|
157
|
+
u2: { name: 'Bob', age: 17 },
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const greetAdult = (id: string) => {
|
|
161
|
+
const result = pipe(
|
|
162
|
+
fromNullable(users[id]), // Option<{ name, age }>
|
|
163
|
+
filterWith((u) => u.age >= 18), // None if under 18
|
|
164
|
+
mapWith((u) => `Hello, ${u.name}!`),
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
return match(result, {
|
|
168
|
+
some: (greeting) => greeting,
|
|
169
|
+
none: () => 'User not found or not an adult',
|
|
170
|
+
});
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
greetAdult('u1'); // "Hello, Alice!"
|
|
174
|
+
greetAdult('u2'); // "User not found or not an adult"
|
|
175
|
+
greetAdult('u3'); // "User not found or not an adult"
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`Option` connects to `Result` through `mapToResult` -- it converts `None` into a typed error so you can continue in a Result pipeline:
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
import { mapToResult, fromNullable } from '@railway-ts/pipelines/option';
|
|
182
|
+
import { match } from '@railway-ts/pipelines/result';
|
|
183
|
+
|
|
184
|
+
const option = fromNullable(users['u3']); // None
|
|
185
|
+
const result = mapToResult(option, 'User not found');
|
|
186
|
+
// Err('User not found')
|
|
187
|
+
|
|
188
|
+
match(result, {
|
|
189
|
+
ok: (user) => console.log(user.name),
|
|
190
|
+
err: (error) => console.error(error), // "User not found"
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## Step 6: validate -- Parse Untrusted Data
|
|
197
|
+
|
|
198
|
+
So far we've been starting pipelines with `ok(10)` -- a known good value. In the real world, data comes from users, APIs, and databases. It's `unknown` until you check it.
|
|
199
|
+
|
|
200
|
+
The schema system validates untrusted data and returns a `Result`:
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
import { validate, object, required, chain, string, parseNumber, min } from '@railway-ts/pipelines/schema';
|
|
204
|
+
import { match } from '@railway-ts/pipelines/result';
|
|
205
|
+
|
|
206
|
+
const userSchema = object({
|
|
207
|
+
name: required(string()),
|
|
208
|
+
age: required(chain(parseNumber(), min(18))),
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
const result = validate({ name: 'Alice', age: '25' }, userSchema);
|
|
212
|
+
|
|
213
|
+
match(result, {
|
|
214
|
+
ok: (user) => console.log(user),
|
|
215
|
+
// { name: 'Alice', age: 25 } -- age was parsed from string to number
|
|
216
|
+
err: (errors) => console.error(errors),
|
|
217
|
+
// every validation error, with field paths
|
|
218
|
+
});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Validators compose with `chain` -- each step feeds into the next. `parseNumber()` converts a string to a number, then `min(18)` checks the range. If any step fails, the error includes the field path so you know exactly where the problem is.
|
|
222
|
+
|
|
223
|
+
All errors are collected, not just the first one:
|
|
224
|
+
|
|
225
|
+
```typescript
|
|
226
|
+
const result = validate({ name: 123, age: 'not a number' }, userSchema);
|
|
227
|
+
|
|
228
|
+
match(result, {
|
|
229
|
+
ok: (user) => console.log(user),
|
|
230
|
+
err: (errors) => {
|
|
231
|
+
// [
|
|
232
|
+
// { path: ['name'], message: 'Must be a string' },
|
|
233
|
+
// { path: ['age'], message: 'Must be a valid number' },
|
|
234
|
+
// ]
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## Step 7: Putting It All Together
|
|
242
|
+
|
|
243
|
+
Now you have all the pieces. Here's a complete pipeline that validates input, transforms it, and handles the result. This example uses `fromPromiseWithError` to safely convert Promises that can reject into `Result` values:
|
|
244
|
+
|
|
245
|
+
```typescript
|
|
246
|
+
import { pipeAsync } from '@railway-ts/pipelines/composition';
|
|
247
|
+
import { flatMapWith, mapWith, match, fromPromiseWithError } from '@railway-ts/pipelines/result';
|
|
248
|
+
import {
|
|
249
|
+
validate,
|
|
250
|
+
object,
|
|
251
|
+
required,
|
|
252
|
+
chain,
|
|
253
|
+
string,
|
|
254
|
+
parseNumber,
|
|
255
|
+
min,
|
|
256
|
+
email,
|
|
257
|
+
formatErrors,
|
|
258
|
+
} from '@railway-ts/pipelines/schema';
|
|
259
|
+
|
|
260
|
+
// 1. Define the shape of valid input
|
|
261
|
+
const orderSchema = object({
|
|
262
|
+
email: required(chain(string(), email())),
|
|
263
|
+
quantity: required(chain(parseNumber(), min(1))),
|
|
264
|
+
item: required(string()),
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
// 2. Business logic as plain functions that return Results
|
|
268
|
+
const checkInventory = (order: { item: string; quantity: number }) =>
|
|
269
|
+
// fromPromiseWithError wraps a Promise into a Result,
|
|
270
|
+
// mapping rejection through your error function
|
|
271
|
+
fromPromiseWithError(
|
|
272
|
+
fetch(`/api/inventory/${order.item}`).then((r) => r.json()),
|
|
273
|
+
() => [{ path: ['item'], message: 'Inventory check failed' }],
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
// 3. The pipeline
|
|
277
|
+
const processOrder = async (input: unknown) => {
|
|
278
|
+
const result = await pipeAsync(
|
|
279
|
+
validate(input, orderSchema),
|
|
280
|
+
flatMapWith(checkInventory),
|
|
281
|
+
mapWith((inv) => ({
|
|
282
|
+
confirmed: true,
|
|
283
|
+
available: inv.inStock,
|
|
284
|
+
})),
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
return match(result, {
|
|
288
|
+
ok: (order) => ({ success: true, data: order }),
|
|
289
|
+
err: (errors) => ({ success: false, errors: formatErrors(errors) }),
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
---
|
|
295
|
+
|
|
296
|
+
## What's Next
|
|
297
|
+
|
|
298
|
+
You now understand the core: `Result`, `Option`, `map`, `flatMap`, `pipe`, `match`, `validate`.
|
|
299
|
+
|
|
300
|
+
- **[Recipes](RECIPES.md)** -- Patterns for real work: async pipelines, error recovery, validation, Standard Schema
|
|
301
|
+
- **[API Reference](API.md)** -- Every function signature and description
|