Commit 7668fda9 by liimin

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

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