微信小程序简单请求封装缓存时长(单位: 秒) 微信小程序简单请求封装缓存时长(单位: 秒)

微信小程序简单请求封装缓存时长(单位: 秒)

module.exports = {
  version: "5.0",
  note: '优化接口调用流程',
  subDomain: "d88f68675a2d3ad69db409865fafb24d", // 如果你的域名是: https://127.0.0.1/abcd 那么这里只要填写 abcd
  appid: "wxe1a52dbd6dda26f0", // 您的小程序的appid,购物单功能需要使用
  shareProfile: '百款精品商品,总有一款适合您' // 首页转发的时候话术
}//config.js文件
const CONFIG = require('../config.js')
const REQUEST_CACHE = []
const API_BASE_URL = 'https://127.0.0.1'
/**
 * 简单请求封装
 * url: 请求地址
 * data: 请求内容
 * method: 请求方法
 * cache: 缓存时长(单位: 秒)
 */
function FetchRequest(url, data, method = 'GET', cache = 0, header = {}, noSubDomain = false) {
  var request_key = GetStorageKey(url, method);
  console.log(111, cache)
  if (cache) {
    return new Promise(Storage);
  } else {
    return new Promise(Request);
  }

  /**
   * 缓存相关
   */
  function Storage(resolve, reject) {
    wx.getStorage({
      key: request_key,
      success: StorageSuccess,
      fail: StorageError
    })

    /**
     * 成功回调
     */
    function StorageSuccess(store) {
      if (CheckCache(store.data)) {
        resolve(store.data);
      } else {
        Request(resolve, reject);
      }
    }

    /**
     * 异常处理
     */
    function StorageError(err) {
      Request(resolve, reject);
    }
  }

  /**
   * 请求接口
   */
  function Request(resolve, reject) {
    // if (CheckRequest(request_key)) {
    //   return;
    // }
    SaveRequest(request_key);
    let _url = API_BASE_URL + '/' + CONFIG.subDomain + url
    if (noSubDomain) {
      _url = API_BASE_URL + url
    }
    wx.request({
      url: _url,
      method: method.toUpperCase(),
      data: data,
      header: header,
      success: FetchSuccess,
      fail: FetchError,
      complete: RequestOver
    })

    /**
     * 成功回调
     */
    function FetchSuccess(res) {
      SaveCache(res);
      if (res.statusCode >= 200 && res.statusCode < 300) {
        resolve(res);
      } else {
        FetchError(res.data);
        switch (res.statusCode) {
          case 403:
            // 业务逻辑处理
            break
        }
      }
    }

    /**
     * 异常处理
     */
    function FetchError(err) {
      if (err) {
        wx.showToast({
          title: err.errMsg || err.message,
          icon: 'none',
          duration: 3000
        })
      }
      reject(err);
    }
  }

  /**
   * 保存缓存信息
   */
  function SaveCache(res) {
    if (cache > 0 && res.statusCode >= 200 && res.statusCode < 300) {
      res.timestamp = Date.parse(new Date()) + cache * 1000;
      wx.setStorage({
        key: GetStorageKey(url, method),
        data: res,
      })
    }
  }

  /**
   * 验证缓存是否过期
   */
  function CheckCache(data) {
    return data.timestamp < Date.parse(new Date());
  }

  function RequestOver() {
    RemoveRequest(request_key);
  }
}

/**
 * 并发请求
 * 没做缓存等处理
 */
function FetchRequestAll(data) {
  return new Promise(function (resolve, reject) {
    Promise.all(data).then(res => {
      resolve(res)
    })
  })
}
function CheckRequest(key) {
  return REQUEST_CACHE.indexOf(key) >= 0;
}

function SaveRequest(key) {
  var index = REQUEST_CACHE.indexOf(key);
  if (index <= 0) {
    REQUEST_CACHE.push(key);
  }
}

function RemoveRequest(key) {
  var index = REQUEST_CACHE.indexOf(key);
  if (index >= 0) {
    REQUEST_CACHE.splice(index, 1);
  }
}

function GetStorageKey(url, method) {
  return `${method.toUpperCase()}:${url.toUpperCase()}`
}

/**
 * 小程序的promise没有finally方法,自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}

module.exports = {
  fetchRequest: FetchRequest,
  cacheTime: 1800,
  fetchRequestAll: FetchRequestAll
}
/**
     * 示例:
     * 调用接口封装方法
     */
    api.fetchRequest('/banner/list', {
      key: 'mallName'
    }).then(function(res) {
      if (res.data.code == 404) {
        wx.showModal({
          title: '提示',
          content: '请在后台添加 banner 轮播图片',
          showCancel: false
        })
      } else {
        that.setData({
          banners: res.data.data
        });
      }
    }).catch(function(res) {
      wx.showToast({
        title: res.data.msg,
        icon: 'none'
      })
    })

评论 0

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论