express-transmit

event dispatch for express

express-transmit

An express.js utility for firing off named events that you expect to callback.

This is a slight change over an eventing system in that you expect a callback to be called, and you want control over the response; for example, firing off requests to either an API or stubbing local data based on configuration.

npm install express-transmit
var express = require('express'),
    expressTransmit = require('express-transmit'),
    app = express.createServer(),
    http = require('http');
 
app.eventRouter = expressTransmit(app);
 
// Provide an endpoint; external for prod, dummy data for development 
app.configure('production', function(){
  app.transmit.provide(':method/data/:collection/:id', function(paramsdatacallback){
    http.get('http://myapi.com/users/' + params.id, function(res){
      var chunks = [];
 
      res.on('data', function(chunk){
        chunks.push(chunk);
      });
 
      res.on('end', function(){
        callback(null, JSON.parse(chunks.join(''));
      });
    }).on('error', function(error){
      callback(error);
    });
  });
});
 
app.configure('development', function(){
  app.transmit.provide(':method/data/:collection/:id', function(paramsdatacallback){
    callback(null, { 
      id: 1,
      name: 'Jack' 
    });
  });
});
 
// Perform a request 
app.get('/api/users/1', function(reqres){
  app.transmit.request('get/data/users/1', function(paramsdatafunction(errdata){
    if(!err){
      res.json(data);
    }else{
      res.json({ error: err.message });
    }
  });
});