[Javascript] Wrap an API with a Proxy
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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();
以上是关于[Javascript] Wrap an API with a Proxy的主要内容,如果未能解决你的问题,请参考以下文章
javascript first_word_wrap_to_span.js
javascript last_word_wrap_to_span.js
javascript Obalitkaždýprvek/ Wrap元素与其他
RecyclerView wrap_content 不适用于 API 23 及更高版本