Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- console.clear();
- function logMethods({ log }) {
- return target => {
- const proto = target.prototype;
- Object.getOwnPropertyNames(proto)
- .filter(n => n !== 'constructor')
- .map(n => ({
- key: n,
- pd: Object.getOwnPropertyDescriptor(proto, n)
- }))
- .filter(({ pd }) => typeof pd.value === 'function')
- .forEach(({ key, pd }) => {
- const orig = pd.value;
- pd.value = function() {
- setTimeout(() => log({ key, className: target.name }), 0);
- return orig.apply(this, arguments);
- };
- Object.defineProperty(proto, key, pd);
- });
- };
- }
- function logTime({ logTo }) {
- return (target, key, pd: PropertyDescriptor) => {
- const origMeth = pd.value;
- pd.value = function() {
- const startTime = Date.now(),
- result = origMeth.apply(this, arguments),
- duration = Date.now() - startTime,
- logf = d =>
- logTo.call(this, {
- duration: d,
- method: key,
- class: target.constructor.name
- });
- if (
- result &&
- (result instanceof Promise || result.constructor.name === 'Promise')
- )
- Promise.all([result]).then(r => logf(Date.now() - startTime));
- else logf(duration);
- return result;
- };
- };
- }
- @logMethods({
- log: ({ key, className }) =>
- console.log(`call the '${key}' method of class '${className}'`)
- })
- class MyClass {
- static options = {
- logTo: MyClass.prototype.log
- };
- @logTime(MyClass.options)
- async test(...args) {
- await this.delay(1000);
- return 'ok';
- }
- @logTime(MyClass.options)
- async delay(ms) {
- await new Promise(res => setTimeout(res, ms));
- }
- @logTime(MyClass.options)
- log(...o) {
- console.log(...o);
- }
- }
- (async () => {
- let m = new MyClass();
- await m.test();
- m.log('decorators are awesome!');
- })();
- /*
- console out:
- call the 'test' method of class 'MyClass'
- call the 'delay' method of class 'MyClass'
- { duration: 1006, method: 'delay', class: 'MyClass' }
- { duration: 1010, method: 'test', class: 'MyClass' }
- decorators are awesome!
- { duration: 0, method: 'log', class: 'MyClass' }
- call the 'log' method of class 'MyClass'
- */
Add Comment
Please, Sign In to add comment