How does it glue together?
Writing REST API in Marble.js isn't hard as you might think. The developer has to understand mostly only the main building block which is the Effect and how the data flows through it.
The aim of this chapter is to demonstrate how building blocks described in previous chapters glue together. For ease of understanding, lets build a tiny RESTful API for user handling. Lets omit the implementation details of database access and focus only on the Marble.js related things.
1
import { createServer, combineRoutes, httpListener, r, HttpError, HttpStatus } from '@marblejs/http';
2
import { logger$ } from '@marblejs/middleware-logger';
3
import { bodyParser$ } from '@marblejs/middleware-body';
4
import { requestValidator$, t } from '@marblejs/middleware-io';
5
import { catchError, mergeMapTo, mergeMap, mapTo, map } from 'rxjs/operators';
6
import { of, throwError, from } from 'rxjs';
7
import { IO } from 'fp-ts/lib/IO';
8
import { pipe } from 'fp-ts/lib/function';
9
​
10
/*------------------------
11
πŸ‘‡ utility functions
12
-------------------------*/
13
​
14
const getUserCollection = () =>
15
from([{ id: '1' }]);
16
​
17
const getUserById = (id: string) =>
18
id === '1'
19
? of({ id: '1', name: 'Test' })
20
: throwError(new Error('User not found'));
21
​
22
/*------------------------
23
πŸ‘‡ USERS API definition
24
-------------------------*/
25
​
26
const validateRequest = requestValidator$({
27
params: t.type({
28
id: t.string,
29
}),
30
});
31
​
32
const getUserList$ = r.pipe(
33
r.matchPath('/'),
34
r.matchType('GET'),
35
r.useEffect(req$ => req$.pipe(
36
mergeMap(getUserCollection),
37
map(body => ({ body })),
38
)),
39
);
40
​
41
const getUser$ = r.pipe(
42
r.matchPath('/:id'),
43
r.matchType('GET'),
44
r.useEffect(req$ => req$.pipe(
45
validateRequest,
46
mergeMap(req => pipe(
47
getUserById(req.params.id),
48
catchError(() => throwError(() =>
49
new HttpError('User does not exist', HttpStatus.NOT_FOUND)
50
))
51
)),
52
map(body => ({ body })),
53
)),
54
);
55
​
56
const users$ = combineRoutes('/users', [
57
getUser$,
58
getUserList$,
59
]);
60
​
61
​
62
/*------------------------
63
πŸ‘‡ ROOT API definition
64
-------------------------*/
65
​
66
const root$ = r.pipe(
67
r.matchPath('/'),
68
r.matchType('GET'),
69
r.useEffect(req$ => req$.pipe(
70
mapTo({ body: `API version: v1` }),
71
)),
72
);
73
​
74
const api$ = combineRoutes('/api/v1', [
75
root$,
76
users$,
77
]);
78
​
79
​
80
/*------------------------
81
πŸ‘‡ SERVER definition
82
-------------------------*/
83
​
84
const middlewares = [
85
logger$(),
86
bodyParser$(),
87
];
88
​
89
const effects = [
90
api$,
91
];
92
​
93
const server = createServer({
94
port: 1337,
95
listener: httpListener({ middlewares, effects }),
96
});
97
​
98
const main: IO<void> = async () =>
99
await (await server)();
100
​
101
main();
Copied!
Last modified 2mo ago
Copy link