[Javascript] Wrap an API with a Proxy
Proxies allow you to use functions that haven't yet been defined on an object. This means that you can invoke a function then create that function if it works with your API. This lesson shows you how to create an API around a rest service so that you can name each get request as a function on the Proxy.
Imaging you need to call API with fetch for multi API endpoints, we can create multi API call functions, with some duplicate code. Proxy can help us to reduce the level of repeation.
const API_ROOT = "https://swapi.co/api"; const createApi = url => { return new Proxy( { headers: { "Content-Type": "application/json" } }, { get: (target, key) => { return async function(id) { const response = await fetch(`${url}/${key}/${id}`, {}, target); if (response.ok) { return response.json(); } return Promise.reject("Network error"); }; } } ); }; const api = createApi(API_ROOT);
export const peopleApi = api.people; export const planetsApi = api.planets; export const starshipsApi = api.starships; async function go() { const people = await peopleApi(1); console.log(people); const planets = await planetsApi(1); console.log(planets); const starships = await starshipsApi(1); console.log(starships); } go();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-02-07 [Hyperapp] Render Text with JSX in Hyperapp
2018-02-07 [Hyperapp] Interact with the State Object through Hyperapp Action functions
2018-02-07 [ReactVR] Start a Virtual Reality Project Using the React VR CLI
2017-02-07 [NPM] Run npm scripts with git hooks
2017-02-07 [NPM] Use custom config settings in your npm scripts
2017-02-07 [React] Use Jest's Snapshot Testing Feature
2017-02-07 [NPM] Use package.json variables in npm scripts