Effects

Last updated last month

Effect is the main building block of the whole framework. Using its generic interface we can define API endpoints (so called: Effects), middlewares and error handlers (see next chapters).

The simplest implementation of API endpoint can look like this:

const endpoint$ = EffectFactory
.matchPath('/')
.matchType('GET')
.use(req$ => req$.pipe(
mapTo({ body: `Hello, world!` })
));

The sample Effect above resolves every HTTP request that matches to root / path and GET method type and at the end responds with Hello, world! message. Simple as hell, right?

Every API Effect request has to be mapped to object which can contain attributes like body, status or headers. If status code or headers are not passed, then API by default will respond with 200 status and application/json Content -Type header.

A little bit more complex example can look like this:

const postUser$ = EffectFactory
.matchPath('/user')
.matchType('POST')
.use(req$ => req$.pipe(
map(req => req.body),
switchMap(Dao.postUser),
map(response => ({ body: response }))
);

The example above will match every POST request that matches to /user url. Using previously parsed POST body (see bodyParser$ middleware) we can map it to sample DAO which returns a response object as an action confirmation.