-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.ts
42 lines (35 loc) · 1.13 KB
/
example.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import {type Box, all, flat, map, nah, or, pipe, tap, yep} from './lib.js';
class HttpError extends Error {}
class ParseError extends Error {}
const req = (url: string): Box<Response, HttpError> =>
fetch(url)
.then(yep)
.catch(() => nah(new HttpError('http error')));
const parse = <T>(res: Response): Box<T, ParseError> =>
res
.json()
.then((json) => yep(json as T))
.catch(() => nah(new ParseError('json parse error')));
const checkStatus = (res: Response) =>
res.status >= 400 ? nah(new HttpError('status error')) : yep(res);
const getPokemon = (name: string) =>
pipe(
yep(`https://pokeapi.co/api/v2/pokemon/${name}`),
flat(req),
tap((res) =>
console.log(`Requested ${name} with response status ${res.status}`),
),
flat(checkStatus),
flat(parse<{weight: number; name: string}>),
);
const program = pipe(
yep(['ditto', 'onix']),
flat((names) => all(names.map(getPokemon))),
map(([v, w]) =>
v.weight < w.weight
? `${w.name} heavier then ${v.name}`
: `${v.name} heavier then ${w.name}`,
),
or((e) => yep(`recovered err: ${e.message}`)),
);
program.then(console.log);