Created
April 30, 2019 01:02
-
-
Save effe-megna/2b81a4df8c05259c107678a19ec8e279 to your computer and use it in GitHub Desktop.
Some Injection
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
| function getInstanceMethodNames (obj) { | |
| return Object | |
| .getOwnPropertyNames (Object.getPrototypeOf (obj)) | |
| .filter(name => (name !== 'constructor' && typeof obj[name] === 'function')); | |
| } | |
| function getInstanceStaticMethodNames (Class) { | |
| return Object.getOwnPropertyNames(Class) | |
| .filter(prop => typeof Class[prop] === "function"); | |
| } | |
| const state = { | |
| accessToken: "1234", | |
| baseUrl: "https://lol" | |
| } | |
| const injection = fn => { | |
| return (args) => { | |
| console.log(args) | |
| if (typeof args !== "object") { | |
| throw "injection fun wrapped must be called with an object" | |
| } | |
| return fn({ ...state, ...args }) | |
| } | |
| } | |
| const customMiddleWare = store => next => action => { | |
| console.log("Middleware triggered:", action); | |
| next(action); | |
| } | |
| const myFun = ({ accessToken, baseUrl, gg }) => { | |
| console.log(accessToken, baseUrl, gg) | |
| } | |
| const mySecondFun = injection(({ accessToken, baseUrl, wp }) => { | |
| console.log(accessToken, baseUrl, wp) | |
| }) | |
| const myFunEnhanced = injection(myFun) | |
| myFunEnhanced({ gg: "enhanced" }) | |
| mySecondFun({ wp: "already wrapped" }) | |
| class SomeMethods { | |
| static fetchTheSense({ | |
| accessToken, | |
| baseUrl, | |
| id | |
| }) { | |
| console.log("fetchTheSense", accessToken, baseUrl, id) | |
| } | |
| } | |
| const wrapMethodsWithInjection = instance => { | |
| getInstanceMethodNames(instance).map(n => instance.__proto__[n] = injection(instance.__proto__[n])) | |
| } | |
| const wrapStaticMethodsWithInjection = Class => { | |
| getInstanceStaticMethodNames(Class).map(n => Class[n] = injection(Class[n])) | |
| } | |
| const classInstance = new SomeMethods() | |
| wrapMethodsWithInjection(classInstance) | |
| wrapStaticMethodsWithInjection(SomeMethods) | |
| getInstanceStaticMethodNames(SomeMethods).map(x => console.log(x)) | |
| SomeMethods.fetchTheSense({ id: "ID INjectable" }) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment