Experimental: Don't use for production! Use together with websocket-router-server
npm install websocket-router-client
import { Receiver, WebsocketRouter } from "websocket-router-client";
var middleware = function(response, next) {
console.log(response.data);
next(); // calls next callback in chain
}
var receive = new Receiver();
receive.post("message", middleware, function(response, next) {
console.log(response);
});
receive.error("post", "message", function(response, next) {
console.log("Post message failed");
next(); // calls error for status code, response.headers.status
});
// Register error hooks
receive.errorCode(403, function(response, next) {
console.log("403 FAIL");
next(); // calls default error hook
});
var router = new WebsocketRouter("ws://localhost:4044", receive);
router.on("connect", function() {
router.post("message", "Hello");
});
- constructor()
-
get (route, ...callbacks) // Registers callbacks for get route. Callbacks are chained using a middleware pattern. See Middleware pattern section
-
post (route, ...callbacks) // Registers callbacks for post route. Callbacks are chained using a middleware pattern.
-
put (route, ...callbacks) // Registers callbacks for put route. Callbacks are chained using a middleware pattern.
-
delete (route, ...callbacks) // Registers callbacks for delete route. Callbacks are chained using a middleware pattern.
-
error (type, route, ...callbacks) // Registers error handler for route. Errors are chained using a middleware pattern.
-
errorCode (code, ...callbacks) // Registers error handler for a server error code.
-
defaultErrorHandler (code, ...callbacks) // Registers default error handler.
- constructor (url, receiver) // Url to server including port, ex ws://localhost:4044, and an instance of receiver class
-
send (type, route, data [, headers]) // Sends data to server
-
post (route, data [, headers]) // Short version of send
-
get (route, data [, headers]) // Short version of send
-
put (route, data [, headers]) // Short version of send
-
delete (route, data [, headers]) // Short version of send
-
on (event, callback) // Registers event listeners (only one listener per event)
- connect ()
- close ()
- error ()
- message (response) // called before message goes to receiver
- type (string) // get, post, put or delete
- route (string)
- data (*any)
- headers (object) // status is only required
All callbacks and error handlers receives a response object and a next function to pass along to the next method in the callback/errorhandler queue. Example
var cb = function(response, next) {
// do something with response
next(); // call next callback in queue
}