Effects
Effect is the main building block of the whole framework. It is just a function that returns a stream of events. Using its generic interface we can define API endpoints, event handlers or middlewares.
Building your own Effect
Marble.js HttpEffect is a more specialized form of Effect for processing HTTP requests. Its responsibility is to map every incoming request to response object.
The Effect above responds to incoming request with "Hello, world!" message. In case of HTTP protocol each incoming request has to be mapped to an object with body, status or headers attributes. If the status code or headers are not defined, then the API by default responds with 200 OK
status and Content-Type: application/json
header.
Every Marble.js Effect is eagerly bootstrapped on app startup with its own hot Observable. It means that a function can act as a constructor and a returned stream as a place "where the magic happens". It gives you a set of possibilities in terms of optimization, so e.g. you can inject all required context readers during the app startup only once.
In order to route our first HttpEffect, we have to define the path and method that the incoming request should be matched to. The simplest implementation of an HTTP API endpoint can look like this.
Let's define a little bit more complex endpoint.
The example above will match every POST request that matches to /user
url. Using previously parsed body (see bodyParser$ middleware) we can flat map it to other stream and map again to HttpEffectResponse
object as an action confirmation.
Deprecation warning
With an introduction of Marble.js 4.0, old EffectFactory
HTTP route builder does not exist anymore. Please user.pipe
builder instead.
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:
url
method
headers
body (see bodyParser$ section)
params (see routing chapter)
query (see routing chapter)
res (HttpResponse)
For more details about available API offered in http.IncomingMessage
, please visit official Node.js docummentation.
HttpResponse
Response 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.
Since Marble.js version 3.0, HttpResponse object is accessible via req.res
attribute of every HttpRequest.
For more details about the available API offered in http.ServerResponse
, please visit official Node.js docummentation.
Last updated