const app = require('express')();
const bodyParser = require('body-parser');
const { EventEmitter } = require('events');
const profiles = new EventEmitter();
profiles.on('middleware', ({ req, name, elapsedMS }) => {
console.log(req.method, req.url, ':', name, `${elapsedMS}ms`);
});
app.use(wrap(function block(req, res, next) {
setTimeout(() => next(), 1000);
}));
app.use(wrap(bodyParser.json()));
app.post('*', function(req, res) {
res.send('Hello, world!');
});
app.listen(3000);
function wrap(fn) {
return function(req, res, next) {
const start = Date.now();
fn(req, res, function() {
profiles.emit('middleware', {
req,
name: fn.name,
elapsedMS: Date.now() - start
});
next.apply(this, arguments);
});
};
}