Guest User

Untitled

a guest
Jan 24th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. console.clear();
  2.  
  3. function logMethods({ log }) {
  4. return target => {
  5. const proto = target.prototype;
  6. Object.getOwnPropertyNames(proto)
  7. .filter(n => n !== 'constructor')
  8. .map(n => ({
  9. key: n,
  10. pd: Object.getOwnPropertyDescriptor(proto, n)
  11. }))
  12. .filter(({ pd }) => typeof pd.value === 'function')
  13. .forEach(({ key, pd }) => {
  14. const orig = pd.value;
  15. pd.value = function() {
  16. setTimeout(() => log({ key, className: target.name }), 0);
  17. return orig.apply(this, arguments);
  18. };
  19. Object.defineProperty(proto, key, pd);
  20. });
  21. };
  22. }
  23.  
  24. function logTime({ logTo }) {
  25. return (target, key, pd: PropertyDescriptor) => {
  26. const origMeth = pd.value;
  27. pd.value = function() {
  28. const startTime = Date.now(),
  29. result = origMeth.apply(this, arguments),
  30. duration = Date.now() - startTime,
  31. logf = d =>
  32. logTo.call(this, {
  33. duration: d,
  34. method: key,
  35. class: target.constructor.name
  36. });
  37.  
  38. if (
  39. result &&
  40. (result instanceof Promise || result.constructor.name === 'Promise')
  41. )
  42. Promise.all([result]).then(r => logf(Date.now() - startTime));
  43. else logf(duration);
  44. return result;
  45. };
  46. };
  47. }
  48.  
  49. @logMethods({
  50. log: ({ key, className }) =>
  51. console.log(`call the '${key}' method of class '${className}'`)
  52. })
  53. class MyClass {
  54. static options = {
  55. logTo: MyClass.prototype.log
  56. };
  57.  
  58. @logTime(MyClass.options)
  59. async test(...args) {
  60. await this.delay(1000);
  61. return 'ok';
  62. }
  63.  
  64. @logTime(MyClass.options)
  65. async delay(ms) {
  66. await new Promise(res => setTimeout(res, ms));
  67. }
  68.  
  69. @logTime(MyClass.options)
  70. log(...o) {
  71. console.log(...o);
  72. }
  73. }
  74.  
  75. (async () => {
  76. let m = new MyClass();
  77. await m.test();
  78. m.log('decorators are awesome!');
  79. })();
  80.  
  81.  
  82. /*
  83. console out:
  84. call the 'test' method of class 'MyClass'
  85. call the 'delay' method of class 'MyClass'
  86. { duration: 1006, method: 'delay', class: 'MyClass' }
  87. { duration: 1010, method: 'test', class: 'MyClass' }
  88. decorators are awesome!
  89. { duration: 0, method: 'log', class: 'MyClass' }
  90. call the 'log' method of class 'MyClass'
  91. */
Add Comment
Please, Sign In to add comment