pretenderjs / pretender

A mock server library with a nice routing DSL
MIT License
1.26k stars 158 forks source link

Middleware or filters #70

Open saarangsoltani opened 9 years ago

saarangsoltani commented 9 years ago

it would be very handy to have some sort of filtering functionality where a function would be executed before a request handler and if that function returned a value, that value should be sent back as the request response.

server.post('api/orderhistory',{ before: 'authFilter' } , function(request){
  var ORDERS = some data;
  return [200, "Content-Type": "application/json" , ORDERS];
});

server.filter('authFilter', function( request) {
 //chech request headers to see if access token exists otherwise return 
    return [403,{"Content-Type": "application/json"},JSON.stringify({status:'failed',message:'access denied'})];
});

this way you can define a filter once and enforce it on multiple routes. the key is treating a possible response from the filter as response for the request.

jacobthemyth commented 9 years ago

It's on my todo list to put together a pull request for this, but if you need to implement this in the meantime, I did the following:

/*
 * Monkey patch Pretender to allow a "global" handler that returns 401 if the
 * headers are incorrect.
 */
var _handlerForOriginal = Pretender.prototype._handlerFor;
Pretender.prototype._handlerFor = function(verb, path, request){
  if( ! hasAuthHeaders(request) ) {
    return _handlerForOriginal('GET', '/unauthorized', request);
  }
  return _handlerForOriginal.apply(this, arguments);
};

var server = new Pretender(function(){
  this.get('/unauthorized', function (req) {
    return [401, {'Content-Type': 'application/json'}, {error: "unauthorized"}];
  });
});