2023-04-23 23:05:30 +08:00
|
|
|
import { assert } from '../helpers/error';
|
2023-04-25 23:02:05 +08:00
|
|
|
import { isFunction } from '../helpers/isTypes';
|
2023-04-25 22:18:08 +08:00
|
|
|
import { AxiosRequestConfig, AxiosResponse } from './Axios';
|
2023-04-23 23:05:30 +08:00
|
|
|
|
|
|
|
export interface MiddlewareNext {
|
|
|
|
(): Promise<void>;
|
|
|
|
}
|
|
|
|
|
2023-04-25 22:18:08 +08:00
|
|
|
export interface MiddlewareContext {
|
|
|
|
req: AxiosRequestConfig;
|
|
|
|
res: null | AxiosResponse;
|
2023-04-23 23:05:30 +08:00
|
|
|
}
|
|
|
|
|
2023-04-25 22:18:08 +08:00
|
|
|
export interface MiddlewareCallback {
|
|
|
|
(ctx: MiddlewareContext, next: MiddlewareNext): Promise<void>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface MiddlewareUse {
|
2023-04-25 14:28:28 +08:00
|
|
|
/**
|
|
|
|
* 添加中间件
|
|
|
|
*
|
|
|
|
* @param callback 中间件回调
|
|
|
|
*/
|
2023-04-25 22:18:08 +08:00
|
|
|
(callback: MiddlewareCallback): MiddlewareManager;
|
2023-04-23 23:05:30 +08:00
|
|
|
}
|
|
|
|
|
2023-04-25 22:18:08 +08:00
|
|
|
export default class MiddlewareManager {
|
|
|
|
/**
|
|
|
|
* 中间件
|
|
|
|
*/
|
|
|
|
#middlewares: MiddlewareCallback[] = [];
|
2023-04-25 11:54:10 +08:00
|
|
|
|
2023-04-25 14:28:28 +08:00
|
|
|
/**
|
|
|
|
* 添加中间件
|
|
|
|
*/
|
2023-04-25 22:18:08 +08:00
|
|
|
use: MiddlewareUse = (callback: MiddlewareCallback) => {
|
2023-04-25 11:54:10 +08:00
|
|
|
assert(isFunction(callback), 'callback 不是一个 function');
|
2023-04-25 22:18:08 +08:00
|
|
|
this.#middlewares.push(callback!);
|
2023-04-23 23:05:30 +08:00
|
|
|
return this;
|
2023-04-25 14:28:28 +08:00
|
|
|
};
|
2023-04-23 23:05:30 +08:00
|
|
|
|
2023-04-25 22:18:08 +08:00
|
|
|
/**
|
|
|
|
* 包装器
|
|
|
|
*
|
|
|
|
* @param ctx 中间件上下文
|
|
|
|
* @param flush 目标函数
|
|
|
|
*/
|
|
|
|
wrap(ctx: MiddlewareContext, flush: MiddlewareNext) {
|
|
|
|
const runners = [...this.#middlewares, flush];
|
2023-04-25 14:28:28 +08:00
|
|
|
return (function next(): Promise<void> {
|
2023-04-25 22:18:08 +08:00
|
|
|
return runners.shift()!(ctx, next);
|
2023-04-25 14:28:28 +08:00
|
|
|
})();
|
2023-04-23 23:05:30 +08:00
|
|
|
}
|
|
|
|
}
|