midsockets


midsockets is a wrapper around sockjs to provide middleware, routing, and a promise-like request api.

see the api docs for more info

creating a chat app:

server

Create a router which will respond to incoming routes. Mount this router on midsockets.

        
  var api = new midsockets.Router();
  var sockapp = midsockets("/midsockets");
  sockapp.mount("/chat",api);
        
      

You will need to attach it to an HTTP server.

        
  var server = http.createServer(/* e.g., express or connect app */);
  sockapp.listen(server);
        
      

The router can listen for incoming requests. The route passed to on can include any levels of path matches, as well as /:param/ matchers. On most requests, you would return a result by calling res.resolve(). We do not on this subscription route. An unresolved-request will stay open, and events can be emitted on it until it is closed.

We can create an instance of midsockets.Events() for our chat room message pump, as it has a pretty good implementation of events and works with res.listenTo.

        
  var chat_events = new midsockets.Events();

  api.on("/chat/subscription",function(req,res){
    res.listenTo(chat_events,"message",{as: "message"});
  });
        
      

Our /send endpoint is easy. You can see the data passed to RequestClient#post(...) is attached to req.data.

        
  api.on("/chat/send",function(req,res){
    chat_events.emit("message",{body: req.data.body});
    res.resolve();
  });
        
      

client

Initialize midsockets with the midsockets() function, and get a RequestClient to use the promises api.

        
  window.Api = midsockets("/midsockets").requestClient()
        
      

You can create a child RequestGhost (shim for RequestClient) by calling requester() on a RequestClient or RequestGhost. This is useful for removing absolute paths from your implementation. For example, you could pass the result of Api.requester("/chat/room_name") to a ChatRoom class in a more sophisticated application.

        
  var chat = Api.requester("/chat");
        
      

A get() returns a promise, the two most important functions of which are RequestPromise#done(success_callback,error_callback) and RequestPromise#on([event_name],callback). To get our chat subscription, we would .get() it from the RequestClient and listen to events emited on it until it is resolved.

        
  chat.get("/subscription").on("message",function(obj){
    console.log("someone said: "+obj.body);
  }).done(function(){
    console.log("chat has closed");
  });
        
      

Since sending a message requires data to be attached, use the RequestClient#post(route,data) method.

        

  window.sendMessage = function sendMessage(text){
    chat.post("/send",{body:text}).done(function(){
      console.log("message "+text+" has been sent");
    });
  };