网站首页 » » 前端封装的sdk 优秀范例

前端封装的sdk 优秀范例

March 16, 2023

/**

  • 构造函数
  • @param {string} apiKey - API Key
    */

    function MySDK(apiKey) {
    this.apiKey = apiKey;
    this.apiUrl = 'https://api.example.com';
    }

/**

  • GET 请求封装
  • @param {string} endpoint - API 接口地址
  • @param {object} params - 请求参数
  • @returns {Promise} - 返回 Promise 对象
    */

    MySDK.prototype.get = function(endpoint, params) {
    const url = this.apiUrl + endpoint + '?' + this.serializeParams(params);
    return fetch(url, {

     headers: {
       'Authorization': `Bearer ${this.apiKey}`
     }

    }).then(res => res.json());
    }

/**

  • POST 请求封装
  • @param {string} endpoint - API 接口地址
  • @param {object} data - 请求数据
  • @returns {Promise} - 返回 Promise 对象
    */

    MySDK.prototype.post = function(endpoint, data) {
    const url = this.apiUrl + endpoint;
    return fetch(url, {

     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
       'Authorization': `Bearer ${this.apiKey}`
     },
     body: JSON.stringify(data)

    }).then(res => res.json());
    }

/**

  • 序列化请求参数
  • @param {object} params - 请求参数
  • @returns {string} - 返回序列化后的字符串
    */

    MySDK.prototype.serializeParams = function(params) {
    return Object.keys(params)

     .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
     .join('&');

    }

/**

  • 获取用户信息
  • @param {string} userId - 用户 ID
  • @returns {Promise} - 返回 Promise 对象
    */

    MySDK.prototype.getUserInfo = function(userId) {
    return this.get(/users/${userId});
    }

/**

  • 创建订单
  • @param {object} order - 订单信息
  • @returns {Promise} - 返回 Promise 对象
    */

    MySDK.prototype.createOrder = function(order) {
    return this.post('/orders', order);
    }

该 SDK 封装了 GET 和 POST 请求,并提供了序列化参数的方法。同时,该 SDK 也提供了一些具体的业务方法,例如获取用户信息和创建订单等。开发者只需要传递相应的参数即可调用这些方法,无需关心底层的请求和处理逻辑。

使用示例:

const apiKey = 'YOUR_API_KEY';
const mySDK = new MySDK(apiKey);

mySDK.getUserInfo('123').then(userInfo => {
  console.log(userInfo);
}).catch(error => {
  console.error(error);
});

const order = {
  userId: '123',
  amount: 100
};

mySDK.createOrder(order).then(createdOrder => {
  console.log(createdOrder);
}).catch(error => {
  console.error(error);
});