微信小程序 wx.request() 的封装

基于微信小程序的wx.request()方法封装

下面是一个封装方案,满足您提出的所有要求:

复制代码
class HttpService {
  constructor() {
    this.baseUrl = ''; // 基础URL
    this.pendingRequests = new Map(); // 请求缓存池
    this.interceptors = {
      request: [],
      response: []
    };
  }

  // 设置基础URL
  setBaseUrl(url) {
    this.baseUrl = url;
  }

  // 添加拦截器
  useInterceptor(type, handler) {
    if (this.interceptors[type]) {
      this.interceptors[type].push(handler);
    }
  }

  // 核心请求方法
  async request(config) {
    const { 
      url, 
      method = 'GET', 
      data = {}, 
      header = {}, 
      showLoading = false 
    } = config;
    
    // 生成请求唯一标识
    const requestKey = `${method}_${url}_${JSON.stringify(data)}`;
    
    // 检查重复请求
    if (this.pendingRequests.has(requestKey)) {
      return this.pendingRequests.get(requestKey);
    }

    // 请求前拦截处理
    let finalConfig = { url, method, data, header, showLoading };
    for (const interceptor of this.interceptors.request) {
      finalConfig = await interceptor(finalConfig) || finalConfig;
    }

    // 创建请求Promise
    const requestPromise = new Promise((resolve, reject) => {
      // 显示加载状态
      if (finalConfig.showLoading) {
        wx.showLoading({ title: '加载中', mask: true });
      }

      wx.request({
        url: this.baseUrl + finalConfig.url,
        method: finalConfig.method,
        data: finalConfig.data,
        header: finalConfig.header,
        success: async (res) => {
          // 响应后拦截处理
          let processedRes = res;
          for (const interceptor of this.interceptors.response) {
            processedRes = await interceptor(processedRes) || processedRes;
          }
          resolve(processedRes);
        },
        fail: (err) => {
          // 错误处理拦截
          let processedErr = err;
          for (const interceptor of this.interceptors.response) {
            processedErr = interceptor(processedErr) || processedErr;
          }
          reject(processedErr);
        },
        complete: () => {
          // 隐藏加载状态
          if (finalConfig.showLoading) {
            wx.hideLoading();
          }
          // 从缓存池移除
          this.pendingRequests.delete(requestKey);
        }
      });
    });

    // 缓存当前请求
    this.pendingRequests.set(requestKey, requestPromise);
    return requestPromise;
  }

  // 并发请求处理
  all(requests) {
    return Promise.all(requests);
  }

  // 快捷方法:GET
  get(url, params = {}, config = {}) {
    return this.request({
      ...config,
      url,
      method: 'GET',
      data: params
    });
  }

  // 快捷方法:POST
  post(url, data = {}, config = {}) {
    return this.request({
      ...config,
      url,
      method: 'POST',
      data
    });
  }

  // 快捷方法:PUT
  put(url, data = {}, config = {}) {
    return this.request({
      ...config,
      url,
      method: 'PUT',
      data
    });
  }

  // 快捷方法:DELETE
  delete(url, params = {}, config = {}) {
    return this.request({
      ...config,
      url,
      method: 'DELETE',
      data: params
    });
  }
}

// 创建实例
const http = new HttpService();

// 设置基础URL(示例)
http.setBaseUrl('https://api.example.com');

// 添加请求拦截器(示例:添加token)
http.useInterceptor('request', (config) => {
  const token = wx.getStorageSync('token');
  if (token) {
    config.header = {
      ...config.header,
      Authorization: `Bearer ${token}`
    };
  }
  return config;
});

// 添加响应拦截器(示例:错误处理)
http.useInterceptor('response', (response) => {
  if (response.statusCode !== 200) {
    wx.showToast({
      title: `请求错误: ${response.data.message || '未知错误'}`,
      icon: 'none'
    });
    throw new Error('请求失败');
  }
  return response.data;
});

功能说明

  1. 加载状态控制

    • 通过showLoading参数控制是否显示加载动画
    • 默认不显示,需要时手动开启
    • 使用微信原生showLoading/hideLoading方法
  2. 拦截器系统

    • 请求拦截器:在请求发送前修改配置
    • 响应拦截器:处理响应数据和错误
    • 支持添加多个拦截器,按添加顺序执行
  3. 并发请求处理

    • all()方法处理多个并发请求

    • 内部使用Promise.all实现

    • 示例用法:

      复制代码
      const [userData, productList] = await http.all([
        http.get('/user'),
        http.get('/products')
      ]);
  4. 重复请求过滤

    • 使用请求方法+URL+参数的哈希值作为唯一标识
    • 相同请求返回缓存中的Promise对象
    • 避免网络资源浪费
  5. 快捷方法

    • 内置GET/POST/PUT/DELETE快捷方法

    • 简化常用请求调用

    • 示例:

      复制代码
      // GET请求
      const data = await http.get('/api/data', { page: 1 });
      
      // POST请求
      await http.post('/api/submit', { name: 'John' }, { showLoading: true });

使用示例

复制代码
// 获取用户信息
async function fetchUser() {
  try {
    const user = await http.get('/user/profile', null, { showLoading: true });
    console.log('用户数据:', user);
  } catch (error) {
    console.error('获取用户信息失败', error);
  }
}

// 提交表单数据
async function submitForm(data) {
  try {
    const result = await http.post('/form/submit', data, {
      showLoading: true,
      header: { 'Content-Type': 'application/json' }
    });
    wx.showToast({ title: '提交成功' });
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 并发请求示例
async function fetchAllData() {
  try {
    const [orders, messages] = await http.all([
      http.get('/user/orders'),
      http.get('/user/messages')
    ]);
    console.log('订单数据:', orders);
    console.log('消息数据:', messages);
  } catch (error) {
    console.error('数据获取失败', error);
  }
}

这个封装方案具有以下优势:

  1. 完整的拦截器系统支持预处理和后处理
  2. 智能的请求缓存机制避免重复请求
  3. 简洁的API设计降低使用复杂度
  4. 完善的错误处理流程
  5. 灵活的加载状态控制
  6. TypeScript友好,可轻松添加类型定义
相关推荐
陈拉斯2 小时前
无后端的人格测试小程序:当「数据不出设备」变成架构约束,我学到了什么
微信小程序
李纲明8 小时前
微信小程序开了 Skyline 后样式全乱、滚动对不上甚至部分组件不能用?Skyline 怎么接才稳
javascript·微信小程序·小程序·devdiy
李纲明8 小时前
微信小程序等位大桌被小桌占掉或过号回来就闹:先核桌型分队与过号容忍次数,再查门口屏与推送同源
微信小程序·devdiy·等位排队·桌型分队·过号重排·门口屏·推送同源
李纲明20 小时前
微信小程序团课临开课才取消或空位没人补:先核取消时限与自动释放,再查候补确认与预扣回滚
微信小程序·devdiy·团课预约·取消时限·空位释放·候补确认·预扣回滚
用户034187671381 天前
用秒哒做了个拍照识餐小程序,上线两周踩的 4 个坑
微信小程序
李纲明1 天前
微信小程序租赁归还说本来就坏或配件对不上:先核借还点验与随单存证,再查差异计价公示
微信小程序·devdiy·租赁点验·借还拍照·随单存证·差异计价·押金释放
李纲明2 天前
微信小程序次卡跨店对不上账或前台随手改余次:先核流水只增不改与统一日切,再查冲正权限与总部只读
微信小程序·devdiy·核销流水·跨店次卡·日切对账·冲正权限·总部只读
李纲明2 天前
微信小程序维修拆机后口头加价或未确认就开工:先核验机快照与报价确认,再查补充报价与取机核验
微信小程序·devdiy·维修验机·报价确认·报价快照·补充报价·取机核验
wx1qq1com2 天前
一桩带几台车:共享租赁桩位配比、取电与结算闭环设计
物联网·微信小程序·小程序
李纲明2 天前
微信小程序场地长租月底对不上或口头占场撞场:先核合约预约与核销流水出账,再查附加费与转租归属
微信小程序·devdiy·场地长租·月结账单·核销流水·附加费·转租归属