[Javascript] Wrap an API with a Proxy
JavaScriptAPI with an Proxy wrap
2023-09-14 09:00:49 时间
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();
相关文章
- 使用JavaScript调用手机平台上的原生API
- java 11 移除的一些其他内容,更简化的编译运行程序,Unicode 10,移除了不太使用的JavaEE模块和CORBA技术,废除Nashorn javascript引擎,不建议使用Pack200 相关api
- [Javascript] The JSON.stringify API
- [Javascript] JSON.parse API
- [Javascript Natural] Break up language strings into parts using Natural
- [Javascript] Monads
- [Javascript] delete keyword
- [Javascript] The JSON.stringify API
- ArcGIS api for javascript——加载查询结果,悬停显示信息窗口
- 关于 Orbeon form PE 版本使用 JavaScript Embedding API 的一个例子
- JavaScript ES6 Fetch API时需要注意的一个Cookie问题
- 使用JavaScript调用手机平台上的原生API
- 如何比较两个对象以确定第一个对象包含与JavaScript中的第二个对象等效的属性值?
- JavaScript:获取当前日期时间的字符串格式
- 【JavaScript】出现即使设置了ID也获取不到的可能原因与window.onload
- 每天一个JavaScript实例-从一个div元素删除一个段落
- web前端框架Javascript开发基础之JavaScript作用域