import type { RequestHeader } from './interface/common'; // import { createHash } from 'crypto'; // 引入Node.js的内置模块crypto import { Md5 } from 'ts-md5'; function sortObjectKeys(obj: Record): Record { // 获取并排序对象的所有键 try { const sortedKeys = Object.keys(obj).sort(); // 创建一个新对象,它的键按字典序排序 const sortedObj = sortedKeys.reduce((result, key) => { if ( typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key]) ) { // 如果值是一个对象,则递归排序它的键 return { ...result, [key]: sortObjectKeys(obj[key]) }; } // 否则,直接添加键和值 return { ...result, [key]: obj[key] }; }, {}); return sortedObj; } catch (e) { // 包括undefined和null return {}; } } function sortObjectKeysAndStringify(obj: Record): string { // 先排序对象的键,然后将结果转化为字符串 return JSON.stringify(sortObjectKeys(obj)); } const generateToken = ( timestamp: string, method: 'POST' | 'GET', data: any, url: string ): string => { try { let str = ''; if (method === 'POST') { str = sortObjectKeysAndStringify(data); } else { if (!url.includes('?')) str = sortObjectKeysAndStringify({}); // Split the url at the '?', get the second part which is the query string const queryString = url.split('?')[1]; // Split the query string at '&', get an array of 'key=value' strings const keyValuePairs = queryString.split('&'); // Parse the array into an object const params = {}; keyValuePairs.forEach((pair) => { const [key, value] = pair.split('='); params[key] = value; }); str = sortObjectKeysAndStringify(params); } return Md5.hashStr(timestamp + str); } catch (e) { console.log(e); return ''; } }; function request({ baseUrl, url, header, data, method = 'POST', requestInit }: { baseUrl: string; url: string; header: RequestHeader; data?: IReq; method: 'POST' | 'GET'; requestInit?: RequestInit; }): Promise { const timestamp = Date.now().toString(); return fetch(`${baseUrl}${url}`, { method, headers: { 'Content-Type': 'application/json;charset=utf-8', timestamp: timestamp, _csrf: generateToken(timestamp, method, data, url), ...header }, body: JSON.stringify(data), ...requestInit }).then((response) => { if (response.status >= 200 && response.status < 300) { return response.json().then((res) => { if (res?.code === 0) { return res.data; } throw new Error(JSON.stringify(res)); }); } throw new Error(response.statusText); }); } export default request;