Effects

Hello, world!

Effect is the main building block of the whole framework. It is just a function which returns a stream of events. Using its generic interface we can define API endpoints, middlewares, error handlers and much more (see next chapters). Let's define our first "hello world" HttpEffect!

const helloEffect$: HttpEffect = req$ => req$.pipe(
  mapTo({ body: 'Hello, world!' }),
);

The Effect above responds to incoming request with Hello, world! message. In Marble.js, every Effect tries to be referentailly transparent, which means that each incoming request has to be mapped to an object with attributes like body, status or headers. If the status code or headers are not defined, then the API by default responds with 200 status and application/json header.

In order to route our first Effect, we have to define the path and HTTP method that the incoming request should be matched to. The simplest implementation of an HTTP API endpoint can look like this.

const hello$ = r.pipe(
  r.matchPath('/'),
  r.matchType('GET'),
  r.useEffect(helloEffect$));

Lets define a little bit more complex endpoint.

const postUser$ = r.pipe(
  r.matchPath('/user'),
  r.matchType('POST'),
  r.useEffect(req$ => req$.pipe(
    map(req => req.body as User),
    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 example DAO which returns a HttpEffectResponse object as an action confirmation.

Since Marble.js 2.0, you can build HTTP API routes using EffectFactory builder or using new, pipeable functions insider.pipe function.

HttpRequest

Every HttpEffect has an access to two most basics objects created by http.Server. HttpRequest is an abstraction over the 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 the previously described HttpRequest, the HttpResponse object is also 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 information about the res.send method, visit Middlewares chapter.

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

Last updated