码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Wrap an API with a Proxy

时间:2019-02-07 19:07:57      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:wrap   poi   you   cal   javascrip   ret   src   ons   wapi   

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

标签:wrap   poi   you   cal   javascrip   ret   src   ons   wapi   

原文地址:https://www.cnblogs.com/Answer1215/p/10355001.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!