Effects

Hello, world!

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 helloWorld$ = 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:

postUser.effect.ts
const postUser$ = EffectFactory
  .matchPath('/user')
  .matchType('POST')
  .use(req$ => req$.pipe(
    map(req => req.body),
    mergeMap(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.

HttpRequest

Every Effect has an access to two most basics objects created by http.Server. The first one is HttpRequest which is just an abstraction over basic Node.js http.IncomingMessage object. It may be used to access response status, headers and data, but in most scenarios you don't have to deal with all available APIs offered by IncomingMessage class. The most common properties available in request object are:

For more details about available API offered in http.IncomingMessage, please visit official Node.js docummentation.

HttpResponse

Like previously described HttpRequest, the HttpResponse object is also just an abstraction over basic Node.js http.ServerResponse object. Besides the default API, the response object exposes an res.send method, which can be a handy wrapper over Marble.js responding mechanism. For more detailed information about res.send method, visit Middlewares chapter.

For more details about available API offered in http.ServerResponse, please visit official Node.js docummentation.

Last updated