methods.ts
1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { RequestConfig } from "./types";
/**
* 为Request类添加HTTP方法别名
* @param {Object} instance Request实例
*/
export function addMethodAliases(instance: any): void {
// 策略接口:定义方法创建策略
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 });
};
}
}
// 有数据方法策略(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);
});
}