Skip to content

Instantly share code, notes, and snippets.

@muratcorlu
Created June 25, 2013 15:24
Show Gist options
  • Save muratcorlu/5859366 to your computer and use it in GitHub Desktop.
Save muratcorlu/5859366 to your computer and use it in GitHub Desktop.
Connect middleware that creates mockes for rest apis.
var fs = require('fs');
module.exports = function (urlRoot, pathRoot) {
pathRoot = pathRoot.replace(urlRoot, '');
return function(req, res, next){
if (req.url.indexOf(urlRoot) === 0) {
// Ignore querystrings
url = req.url.split('?')[0];
fs.readFile('./' + pathRoot + url + '/'+req.method+'.json', function(err, buf){
if (err) return next(err);
resp = {
headers: {
'Content-Type': 'application/json',
'Content-Length': buf.length
},
body: buf
};
res.writeHead(200, resp.headers);
res.end(resp.body);
});
} else {
next();
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment