Created
May 17, 2021 16:29
-
-
Save DrJume/7a4177a0d8598ac8cec3fc1a820b3da9 to your computer and use it in GitHub Desktop.
JavaScript Proxy object for translating object property accesses to API call urls
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
/** | |
* @typedef API | |
* @property {object} users | |
* @property {()} users.getById | |
* @property {()} users.getByName | |
*/ | |
/** @returns {API} */ | |
function ProxyFactory() { | |
return Proxy({}, handler) | |
} | |
export default ProxyFactory |
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 handler = (props) => ({ | |
get(obj, prop) { | |
return new Proxy(obj, handler([...props, prop])) | |
}, | |
apply(target, thisArg, argumentsList) { | |
const phpFuncPath = props.map(prop => prop.split(/(?<=[a-z])(?=[A-Z])/g).join('_').toLowerCase()).join('/') | |
console.log(phpFuncPath) | |
console.log({ args: argumentsList }) | |
return { success: true } | |
} | |
}) | |
const API = new Proxy(function () { }, handler([])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment