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 understaning 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.
import { createServer, combineRoutes, httpListener, r, HttpError, use, HttpStatus } from'@marblejs/core';import { logger$ } from'@marblejs/middleware-logger';import { bodyParser$ } from'@marblejs/middleware-body';import { requestValidator$, t } from'@marblejs/middleware-io';import { mergeMapTo, mergeMap, catchError, mapTo, map } from'rxjs/operators';import { of, throwError, from } from'rxjs';functiongetUserCollection() {returnfrom([{ id:'1' }]);}functiongetUserById(id:string) {if (id !=='1') {thrownewError('User not found'); }returnof({ id:'1', name:'Test' });}/*------------------------ 👇 USERS API definition-------------------------*/constgetUserValidator$=requestValidator$({ params:t.type({ id:t.string, }),});constgetUserList$=r.pipe(r.matchPath('/'),r.matchType('GET'),r.useEffect(req$ =>req$.pipe(mergeMapTo(getUserCollection()),map(body => ({ body })), )),);constgetUser$=r.pipe(r.matchPath('/:id'),r.matchType('GET'),r.useEffect(req$ =>req$.pipe(use(getUserValidator$),mergeMap(req$ =>of(req$.params.id).pipe(mergeMap(getUserById),map(body => ({ body })),catchError(() =>throwError(newHttpError('User does not exist',HttpStatus.NOT_FOUND) )) )), )),);constusers$=combineRoutes('/users', [ getUser$, getUserList$,]);/*------------------------ 👇 ROOT API definition-------------------------*/constroot$=r.pipe(r.matchPath('/'),r.matchType('GET'),r.useEffect(req$ =>req$.pipe(mapTo({ body:`API version: v1` }), )),);constnotFound$=r.pipe(r.matchPath('*'),r.matchType('*'),r.useEffect(req$ =>req$.pipe(mergeMapTo(throwError(newHttpError('Route not found',HttpStatus.NOT_FOUND) )), )),);constapi$=combineRoutes('/api/v1', [ root$, users$, notFound$,]);/*------------------------ 👇 SERVER definition-------------------------*/constmiddlewares= [logger$(),bodyParser$(),];consteffects= [ api$,];constserver=createServer({ port:1337, httpListener:httpListener({ middlewares, effects }),});server.run();