[英]Dynamically build external API URL and parameters
Today we have an object to keep track an external API usage like this:今天我们有一个 object 来跟踪外部 API 的使用情况,如下所示:
const setParams =
(params) => Object.keys(params).map(
(element) => element + '=' + encodeURIComponent(params[element])).join('&')
const API = {
Common: {
Search: (order) => `Common/Search?${setParams({order})}`,
}}
console.log(API.Common.Search(1)); // "Common/Search?order=1"
However, we still get some typos what could be avoided.但是,我们仍然会遇到一些可以避免的拼写错误。
Is it possible to dynamically set that URL even what we would need to change that API structure a bit?是否可以动态设置 URL 即使我们需要稍微更改 API 结构?
const API = {
Common: {
Search: (order) => `${magicParent}/${magicCurrent}?${params}`,
Another: (login, argA, argB) => `${magicParent}/${magicCurrent}?${magic(params)}`,
}}
console.log(API.Common.Search(1)); // "Common/Search?order=1"
console.log(API.Common.Another(1,2,3)); // "Common/Another?login=1&argA=2&argB=3"
Thanks,谢谢,
Just an idea |只是一个想法| Not tested |
未测试 | Ugly (mutates):
丑陋(变异):
const isObject = // Implement yourself
const injectPath = (obj, path = '') => {
Object.entries(obj).forEach( ([key, value]) => {
if (isObject(value) {
injectPath(value, path + '/' + key;
} else {
// It is a function
obj[key] = value(path);
}
})
}
const API = injectPath({
Common: {
Search: (path) => (order) => `${path}?${setParams({order})}`,
}}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.