Skip to content
do- edited this page Aug 18, 2024 · 15 revisions

Router is an abstract synchronous message processor.

Its sole function is to choose the right destination for a given incoming message and to forward it therein.

This works as for Apache HTTP Server's <VirtualHost> with multiple <Location>s. Or just a switch statement.

Router intercepts both uncaught errors and unhandled error events from child processors and reemits them as its own error events.

The lifecycle is tracked by the means of events-to-winston.

Properties

Name Description
name the name of this router to use in logs etc.
logger A winston Logger
tracker the Tracker listening to the router's events and registering them with logger

Events

Name Description
start Emitted by listen ()
data Emitted by proccess (), the payload is message.
error emitted when a processor throws an error or, being an event emitter itself, emits an error event that it doesn't handle
finish Emitted by close ()

Methods

Final

add (destination)

Registers a new child message processor and sets its router back reference. It must be an object with two synchronous methods:

Name Required? Description
[Router.TEST_MESSAGE] (message) optional to detect if the message is acceptable for this processor
[Router.PROCESS_MESSAGE] (message) required to actually process the message

The argument object is not required to inherit from any common ancestor. It may be an ad hoc object with two lambda valued properties. On the other hand, any Router instance fits too: routers can be nested.

If test is missing, it defaults to () => true. Normally, each router must have such a catch-all processor registered the last (as switch's default clause): at least, to report errors on non-processed messages.

process (message)

Scans the list of previously added destinations, in the order they were added.

Skips all of them having the [Router.TEST_MESSAGE] method not returning true for [Router.TEST_MESSAGE] (message) call.

For the first non-skipped processor, [Router.PROCESS_MESSAGE] (message) is called and undefined is returned.

Throws an Error if all destinations were skipped.

To override

listen ()

Doesn't actually start any listening process but checks all child processors: if error handler is not set, adds one to broadcast the error by emitting own error event.

Emits the 'start' event.

This method should be called from super in any derived router class.

close ()

Removes all event handlers set by listen and emits the 'finish' event.

This method should be called from super in any derived router class.

Clone this wiki locally