Last active
February 12, 2020 01:06
-
-
Save ErickWendel/e9daa773d8d0cc9597755954cfcc43ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const IS_TEST = process.env.NODE_ENV === 'test'; | |
const ONE_SECOND_TIMEOUT = 1000; | |
class Util { | |
static async delayedCall(fn, params, time = ONE_SECOND_TIMEOUT) { | |
return new Promise((resolve, reject) => setTimeout(() => { | |
fn(...params) | |
.then(resolve) | |
.catch(reject); | |
}, time)); | |
} | |
static changeCallBehaviour(apiPromised) { | |
if (IS_TEST) return apiPromised; | |
// eslint-disable-next-line no-proto | |
const methods = apiPromised.__proto__; | |
const functions = Object.getOwnPropertyNames(methods) | |
.map((item) => { | |
const fn = apiPromised[item].bind(apiPromised); | |
return { | |
[item]: async (...args) => Util.delayedCall(fn, args) | |
}; | |
}) | |
.reduce((p, n) => ({ ...p, ...n }), {}); | |
return functions; | |
} | |
} | |
class MyApiPromised { | |
constructor(){ | |
this.message = `${new Date().toISOString()}, 'will execute later!'`; | |
} | |
async get(arg1, arg2) { | |
return `${this.message}, ${arg1}, ${arg2}`; | |
} | |
} | |
const instance = new MyApiPromised(); | |
const changedInstance = Util.changeCallBehaviour(instance); | |
console.log(new Date().toISOString(), 'Starting...'); | |
changedInstance.get('abc', 123).then(console.log); |
da para usar o proxy como exemplo;
const IS_TEST = process.env.NODE_ENV === 'test'; const ONE_SECOND_TIMEOUT = 1000 class Util { static async delayedCall(fn, time = ONE_SECOND_TIMEOUT) { return new Promise((resolve, reject) => setTimeout(() => { fn() .then(resolve) .catch(reject); }, time)); } static changeCallBehaviour(apiPromised) { if (IS_TEST) return apiPromised; const delay = fn => new Proxy(fn, { apply(target, thisArg, argumentsList) { return Util.delayedCall(target.bind(thisArg, ...argumentsList)); }, }); const prototype = apiPromised.__proto__; return Object.getOwnPropertyNames(prototype) .reduce((acc, cur) => { acc[cur] = delay(apiPromised[cur]).bind(apiPromised); return acc; }, {}); } } class MyApiPromised { constructor() { this.message = `${new Date().toISOString()}, 'will execute later!'`; } async get(arg1, arg2) { return `${this.message}, ${arg1}, ${arg2}`; } async custom (arg1) { return `${this.message}, ${arg1}`; } } const instance = new MyApiPromised(); const changedInstance = Util.changeCallBehaviour(instance); console.log(new Date().toISOString(), 'Starting...'); changedInstance.get('abc', 123).then(console.log); changedInstance.custom('abc').then(console.log);
Implementação sensacional!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
da para usar o proxy como exemplo;