12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- /**
- * API 服务类
- * 提供按需引入的方式使用 API
- */
- import * as userApi from '../api/user.js';
- // 导入其他 API 模块
- // import * as orderApi from '../api/order.js';
- // import * as productApi from '../api/product.js';
- import errorHandler from '../utils/errorHandler.js';
- class ApiService {
- constructor() {
- this.apis = {
- user: userApi,
- // order: orderApi,
- // product: productApi
- };
-
- // 为每个API方法添加错误处理包装
- this._wrapApiWithErrorHandling();
- }
-
- /**
- * 为所有API方法添加统一的错误处理
- * @private
- */
- _wrapApiWithErrorHandling() {
- // 遍历所有API模块
- Object.keys(this.apis).forEach(moduleName => {
- const moduleApi = this.apis[moduleName];
-
- // 遍历模块中的所有方法
- Object.keys(moduleApi).forEach(methodName => {
- const originalMethod = moduleApi[methodName];
-
- // 如果是函数,则包装它
- if (typeof originalMethod === 'function') {
- moduleApi[methodName] = async (...args) => {
- try {
- return await originalMethod(...args);
- } catch (error) {
- // 统一处理错误
- this._handleApiError(error, `${moduleName}.${methodName}`);
- // 继续抛出错误,让调用者可以进行自定义处理
- throw error;
- }
- };
- }
- });
- });
- }
-
- /**
- * 统一处理API错误
- * @param {Error} error - 错误对象
- * @param {string} apiName - API名称
- * @private
- */
- _handleApiError(error, apiName) {
- errorHandler.logError(error, apiName);
- // 错误已经在 request.js 中处理过提示,这里不需要重复提示
- }
-
- /**
- * 获取指定模块的 API
- * @param {string} module - API 模块名称
- * @returns {Object} - 对应模块的 API 对象
- */
- get(module) {
- if (!this.apis[module]) {
- console.error(`API 模块 "${module}" 不存在`);
- return {};
- }
- return this.apis[module];
- }
-
- /**
- * 获取用户相关 API
- * @returns {Object} - 用户相关 API 对象
- */
- get user() {
- return this.apis.user;
- }
-
- // 可以添加其他模块的 getter
- // get order() {
- // return this.apis.order;
- // }
-
- // get product() {
- // return this.apis.product;
- // }
- }
- // 创建单例
- const apiService = new ApiService();
- export default apiService;
|