ApiService.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * API 服务类
  3. * 提供按需引入的方式使用 API
  4. */
  5. import * as userApi from '../api/user.js';
  6. // 导入其他 API 模块
  7. // import * as orderApi from '../api/order.js';
  8. // import * as productApi from '../api/product.js';
  9. import errorHandler from '../utils/errorHandler.js';
  10. class ApiService {
  11. constructor() {
  12. this.apis = {
  13. user: userApi,
  14. // order: orderApi,
  15. // product: productApi
  16. };
  17. // 为每个API方法添加错误处理包装
  18. this._wrapApiWithErrorHandling();
  19. }
  20. /**
  21. * 为所有API方法添加统一的错误处理
  22. * @private
  23. */
  24. _wrapApiWithErrorHandling() {
  25. // 遍历所有API模块
  26. Object.keys(this.apis).forEach(moduleName => {
  27. const moduleApi = this.apis[moduleName];
  28. // 遍历模块中的所有方法
  29. Object.keys(moduleApi).forEach(methodName => {
  30. const originalMethod = moduleApi[methodName];
  31. // 如果是函数,则包装它
  32. if (typeof originalMethod === 'function') {
  33. moduleApi[methodName] = async (...args) => {
  34. try {
  35. return await originalMethod(...args);
  36. } catch (error) {
  37. // 统一处理错误
  38. this._handleApiError(error, `${moduleName}.${methodName}`);
  39. // 继续抛出错误,让调用者可以进行自定义处理
  40. throw error;
  41. }
  42. };
  43. }
  44. });
  45. });
  46. }
  47. /**
  48. * 统一处理API错误
  49. * @param {Error} error - 错误对象
  50. * @param {string} apiName - API名称
  51. * @private
  52. */
  53. _handleApiError(error, apiName) {
  54. errorHandler.logError(error, apiName);
  55. // 错误已经在 request.js 中处理过提示,这里不需要重复提示
  56. }
  57. /**
  58. * 获取指定模块的 API
  59. * @param {string} module - API 模块名称
  60. * @returns {Object} - 对应模块的 API 对象
  61. */
  62. get(module) {
  63. if (!this.apis[module]) {
  64. console.error(`API 模块 "${module}" 不存在`);
  65. return {};
  66. }
  67. return this.apis[module];
  68. }
  69. /**
  70. * 获取用户相关 API
  71. * @returns {Object} - 用户相关 API 对象
  72. */
  73. get user() {
  74. return this.apis.user;
  75. }
  76. // 可以添加其他模块的 getter
  77. // get order() {
  78. // return this.apis.order;
  79. // }
  80. // get product() {
  81. // return this.apis.product;
  82. // }
  83. }
  84. // 创建单例
  85. const apiService = new ApiService();
  86. export default apiService;