[Javascript] Wrap an API with a Proxy

使用Proxy简化API调用
本文介绍如何利用JavaScript的Proxy对象来简化API调用过程,通过创建通用的API调用函数,减少重复代码,实现对多个API端点的统一管理和调用。示例中展示了如何针对REST服务创建API,将每个GET请求命名为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();

 

 

转载于:https://www.cnblogs.com/Answer1215/p/10355001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值