createExtensions.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. var captureLastRun = require('last-run').capture;
  3. var releaseLastRun = require('last-run').release;
  4. var metadata = require('./metadata');
  5. var uid = 0;
  6. function Storage(fn) {
  7. var meta = metadata.get(fn);
  8. this.fn = meta.orig || fn;
  9. this.uid = uid++;
  10. this.name = meta.name;
  11. this.branch = meta.branch || false;
  12. this.captureTime = Date.now();
  13. this.startHr = [];
  14. }
  15. Storage.prototype.capture = function() {
  16. captureLastRun(this.fn, this.captureTime);
  17. };
  18. Storage.prototype.release = function() {
  19. releaseLastRun(this.fn);
  20. };
  21. function createExtensions(ee) {
  22. return {
  23. create: function(fn) {
  24. return new Storage(fn);
  25. },
  26. before: function(storage) {
  27. storage.startHr = process.hrtime();
  28. ee.emit('start', {
  29. uid: storage.uid,
  30. name: storage.name,
  31. branch: storage.branch,
  32. time: Date.now(),
  33. });
  34. },
  35. after: function(result, storage) {
  36. if (result && result.state === 'error') {
  37. return this.error(result.value, storage);
  38. }
  39. storage.capture();
  40. ee.emit('stop', {
  41. uid: storage.uid,
  42. name: storage.name,
  43. branch: storage.branch,
  44. duration: process.hrtime(storage.startHr),
  45. time: Date.now(),
  46. });
  47. },
  48. error: function(error, storage) {
  49. if (Array.isArray(error)) {
  50. error = error[0];
  51. }
  52. storage.release();
  53. ee.emit('error', {
  54. uid: storage.uid,
  55. name: storage.name,
  56. branch: storage.branch,
  57. error: error,
  58. duration: process.hrtime(storage.startHr),
  59. time: Date.now(),
  60. });
  61. },
  62. };
  63. }
  64. module.exports = createExtensions;