import { Uni } from '@dcloudio/uni-app' declare const uni : Uni // 定义请求方法的类型 type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'; interface RequestOptions { method ?: HttpMethod; data ?: any; // 请求体 } // 将对象转换为查询字符串的辅助函数 function objectToQueryString(obj : Record) : string { if (!obj) return ''; return Object.keys(obj) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`) .join('&'); } // 获取基础URL的函数 function getBaseUrl() { // @ts-ignore return uni.$globalData?.BASE_URL || 'https://dev.api.leapy.cn/merchant'; } // 封装请求函数 export const request = (endpoint : string, options : RequestOptions = {}) => { const url = `${endpoint}`; return new Promise((resolve, reject) => { uni.request({ url, method: options.method || 'GET', data: options.data || {}, header: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + uni.$store.state.token }, success: (response) => { if (response.statusCode >= 200 && response.statusCode < 300) { if (response.data.code == 500) { uni.$store.commit("logout") reject(response.data); return; } resolve(response.data); } else { reject(new Error(`HTTP error! status: ${response.statusCode}`)); } }, fail: (error) => { console.error('Network request failed:', error); reject(error); }, }); }); }; // 封装 GET 请求 export const get = (endpoint : string, params ?: any) => { const queryString = params ? `?${objectToQueryString(params)}` : ''; return request(`${getBaseUrl()}${endpoint}${queryString}`, { method: 'GET' }); }; // 封装 POST 请求 export const post = (endpoint : string, data ?: any) => { return request(`${getBaseUrl()}${endpoint}`, { method: 'POST', data }); }; // 封装 PUT 请求 export const put = (endpoint : string, data ?: any) => { return request(`${getBaseUrl()}${endpoint}`, { method: 'PUT', data }); }; // 封装 DELETE 请求 export const del = (endpoint : string, data ?: any) => { return request(`${getBaseUrl()}${endpoint}`, { method: 'DELETE', data }); };