Commit 7668fda9 by liimin

refactor: 重构白名单检查逻辑和HTTP方法别名实现

重构白名单检查逻辑,改为检查URL而非method参数
将SignatureResult接口中的非必填字段改为必填
使用策略模式重构HTTP方法别名的实现
优化请求参数处理逻辑,移除对GET/DELETE方法的特殊处理
1 parent 5cf95535
......@@ -124,7 +124,7 @@
});
resultElement.textContent =
`请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
`请求成功:\n请求参数: ${JSON.stringify(result.config.data, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
} catch (error) {
resultElement.textContent = `请求失败: ${error.message}`;
}
......@@ -137,12 +137,15 @@
// 白名单URL列表由SDK内部处理
// 我们只需要在请求参数中添加method参数
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数');
// POST请求使用data传递参数(放在请求体中)
const result = await request.post('/dict/sign/test1', {
"id":6,
"id": 6,
"objs": ["hehe", "haah"],
"dogs":[{"name":"haogou","age":1},{"name":"拉布拉多","age":2}],
"dog":{"name":"haogou","age":1}
});
"dogs": [{"name": "haogou", "age": 1}, {"name": "拉布拉多", "age": 2}],
"dog": {"name": "haogou", "age": 1}
});
resultElement.textContent =
`请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
} catch (error) {
......
......@@ -13,7 +13,8 @@ export function buildURL(baseURL: string = '', url: string = '', params: Record<
let fullURL = baseURL + url;
// 处理GET请求参数或其他方法的URL参数
if ((method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') && Object.keys(params).length) {
// if ((method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') && Object.keys(params).length) {
if (Object.keys(params).length) {
// 使用通用参数处理函数,采用对象索引模式处理数组,支持Java后端
const processedParams = processParams(params, ArrayProcessMode.OBJECT_INDEX) as Array<{key: string, value: string}>;
// 构建查询字符串
......
import type { RequestConfig } from "./types";
/**
* 为Request类添加HTTP方法别名
* @param {Object} instance Request实例
*/
export function addMethodAliases(instance: any): void {
// 添加别名方法
(["get", "post", "put", "delete", "patch"] as const).forEach((method) => {
if (method === "get" || method === "delete") {
// 对于GET、DELETE方法
instance[method] = function (this: any,
url: string,
config: RequestConfig = {}
) {
return this.request({
url,
method: method.toUpperCase(),
...config,
});
// 策略接口:定义方法创建策略
interface MethodStrategy {
createMethod(method: string): Function;
}
// 无数据方法策略(GET、DELETE)
class NoDataMethodStrategy implements MethodStrategy {
createMethod(method: string): Function {
const upperMethod = method.toUpperCase();
return function (this: any, url: string, config: RequestConfig = {}) {
return this.request({ url, method: upperMethod, ...config });
};
} else {
// 对于POST、PUT、PATCH方法
instance[method] = function (this: any,
url: string,
data?: any,
config: RequestConfig = {}
) {
return this.request({
url,
method: method.toUpperCase(),
data,
...config,
});
}
}
// 有数据方法策略(POST、PUT、PATCH)
class WithDataMethodStrategy implements MethodStrategy {
createMethod(method: string): Function {
const upperMethod = method.toUpperCase();
return function (this: any, url: string, data?: any, config: RequestConfig = {}) {
return this.request({ url, method: upperMethod, data, ...config });
};
}
}
// 策略实例
const noDataStrategy = new NoDataMethodStrategy();
const withDataStrategy = new WithDataMethodStrategy();
// 方法与策略的映射
const methodStrategies = new Map<string, MethodStrategy>([
['get', noDataStrategy],
['delete', noDataStrategy],
['post', withDataStrategy],
['put', withDataStrategy],
['patch', withDataStrategy]
]);
// 使用策略模式创建方法别名
methodStrategies.forEach((strategy, methodName) => {
instance[methodName] = strategy.createMethod(methodName);
});
}
\ No newline at end of file
......@@ -19,6 +19,7 @@ import { subscribeEvents } from "./events";
import Trace from "./traces";
import Defaults from "./defaults";
import { initSentry, reportNetworkError } from "./sentry";
import { buildURL } from "./adapter/utils";
interface Interceptors {
request: InterceptorManager<RequestConfig>;
......@@ -82,7 +83,7 @@ class Request {
request<T = any>(
options: RequestConfig = {}
): Promise<ResponseData<T>> & { abort?: () => void } {
console.log("🚀 ~ Request ~ request ~ options:", options)
console.log("🚀 ~ Request ~ request ~ options:", options);
// 合并配置
const config = this.defaults.merge(options);
......@@ -180,19 +181,19 @@ class Request {
console.warn("缺少签名所需的应用ID或密钥");
return config;
}
// 获取请求参数
const params = { ...config.params };
// 检查method参数是否在白名单中并更新参数
if (params.method) {
const updatedParams = await checkWhitelist(params);
config.params = updatedParams;
// 检查当前请求的URL是否在白名单中
const isInWhitelist = await checkWhitelist(config.url!);
// 如果URL在白名单中,将sdctag=true添加到URL和签名参数中
if (isInWhitelist) {
// 检查URL是否已经包含查询参数
params.sdctag = "true";
}
config.params = params;
// 合并URL参数和请求体数据用于签名
const signatureParams = { ...config.params };
if (config.data && typeof config.data === 'object') {
if (config.data && typeof config.data === "object") {
Object.assign(signatureParams, config.data);
}
......@@ -201,14 +202,14 @@ class Request {
appId,
appSecret,
params: signatureParams,
method: config.method || 'GET',
method: config.method || "POST",
});
// 添加签名到请求头
config.headers = {
...config.headers,
"X-App-Id": appId,
...(signature.nonce && { "X-Nonce": signature.nonce }),
...(signature.timestamp && { "X-Timestamp": signature.timestamp }),
"X-Nonce": signature.nonce,
"X-Timestamp": signature.timestamp,
"X-Sign": signature.sign,
};
return config;
......
......@@ -11,8 +11,8 @@ export interface SignatureOptions {
}
export interface SignatureResult {
nonce?: string;
timestamp?: string;
nonce: string;
timestamp: string;
sign: string;
[key: string]: any;
}
......
......@@ -50,8 +50,8 @@ export interface SignatureOptions {
}
export interface SignatureResult {
nonce?: string;
timestamp?: string;
nonce: string;
timestamp: string;
sign: string;
[key: string]: any;
}
......
import Trace from "./traces";
/**
* 检查方法是否在白名单中,如果在则添加sdctag参数
* @param {Object} params 请求参数
* @returns {Promise<Object>} 处理后的参数
* 检查URL是否在白名单中
* @param {string} url 当前请求的URL
* @returns {Promise<boolean>} 是否在白名单中
*/
export async function checkWhitelist(params: Record<string, any>): Promise<Record<string, any>> {
// 如果没有method参数,直接返回原始参数
if (!params.method) {
return params;
export async function checkWhitelist(url: string): Promise<boolean> {
// 如果没有URL参数,返回false
if (!url) {
return false;
}
try {
// 获取白名单URL列表
const whitelistUrls = await Trace.getTraceUrls();
// 检查method是否在白名单中
if (whitelistUrls.includes(params.method)) {
// 如果在白名单中,添加sdctag=true参数
return { ...params, sdctag: 'true' };
}
// 检查当前请求的URL是否在白名单中
return whitelistUrls.includes(url);
} catch (error) {
console.error('检查白名单URL失败:', error);
return false;
}
// 如果不在白名单中或发生错误,返回原始参数
return params;
}
/**
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!