Guest User

Untitled

a guest
Jul 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. // Section 1
  2. var express = require('express');
  3. const bodyParser = require('body-parser');
  4. const { EventEmitter } = require('events');
  5. const morgan = require('morgan');
  6. const app = express();
  7. const profilingEventEmitter = new EventEmitter();
  8.  
  9. // Section 2
  10. profilingEventEmitter.on('middleware', ({ req, name, elapsedMS }) => {
  11. console.log(req.method, req.url, ':', name, `${elapsedMS}ms`);
  12. });
  13.  
  14. // Section 3
  15. var profiler = function(fn) {
  16. if (fn.length === 2) {
  17. return function (req, res) {
  18. const start = Date.now();
  19. res.once('finish', () => profilingEventEmitter.emit('middleware', {
  20. req,
  21. name: fn.name,
  22. elapsedMS: Date.now() - start
  23. }));
  24. return fn.apply(this, arguments);
  25. };
  26. } else if (fn.length === 3) {
  27. return function (req, res, next) {
  28. const start = Date.now();
  29. fn.call(this, req, res, function () {
  30. profilingEventEmitter.emit('middleware', {
  31. req,
  32. name: fn.name,
  33. elapsedMS: Date.now() - start
  34. });
  35. next.apply(this, arguments);
  36. });
  37. };
  38. } else {
  39. throw new Error('Function must take 2 or 3 arguments');
  40. }
  41. }
  42.  
  43. // Section 4
  44. app.use(profiler(morgan('dev')));
  45. app.use(profiler(bodyParser.json()));
  46. app.use(profiler(express.static('public')));
  47.  
  48. // Section 5
  49. app.get('/check', profiler(function userRequestHandling(req, res) {
  50. setTimeout(() => res.send('Done'), 2);
  51. }));
  52.  
  53. app.listen(3000);
Add Comment
Please, Sign In to add comment