a hub for centralizing all your request handlers within your application
A hub for centralizing all your request handlers within your application. Implements the disposable pattern.
npm install transport
Require and initialize transport:
var Transport = require"transport"transport = ;
simpleHandler to handle a request and send the result back:
// Object with all the request handlersvar handlers =// do something with the payloadvar result = doSomethingWithPayloadpayload;// send the result backcallbackresult;;
Add the handler to
Transport. The handlers have to be stored in an
observable-store. This allows for sharing the same handlers between several implementations of
Transport and react accordingly when handlers are added and removed.
var Store = require"observable-store";transportsetReqHandlershandlers;
Make the request to
transportrequest"simpleHandler" "payload"// do something with result;
Let's define a handler that will publish several updates.
var handlers =var stream = getStreampayload;streamon'data' onData;streamon'end' onEnd;;
Now we can open the channel and receive updates:
transportlisten"simpleChannel" "filename"// Will be called when stream closesconsole.log"END OF FILE" data;// Will be called everytime some data is pushedconsole.log"MORE DATA" data;;
transport.listen returns a function. When the
handler also returns a function, it will be called by executing the one returned by
transport.listen. It can be used to stop whatever the
handler started and do some cleanup too.
var handlers =var stream = getStreampayload;streamon"data" onData;streamon"end" onEnd;returnstreamremoveListener"data" onData;streamremoveListener"end" onEnd;;
Now, when calling
transport.listen, we can call the
stop() function returned by the
var stop = transportlisten"closableChannel" "filename" ;// When calling stop, the stop() function returned by the handler will be executed.stop;
A convenient way to bubble up errors is to follow the error first convention:
var handlers =var stream = getStreampayload;streamon"data" onData;streamon"end"onEndnull data;;streamon"error"onEnderror;;;
And now we can handle the errors in the onEnd callback.
transportlisten"closableChannel" "filename"if errorthrow error;// do something with data// ...;