Files
mayfly-go/mayfly_go_web/src/common/Api.ts

154 lines
3.4 KiB
TypeScript
Raw Normal View History

import request from './request';
import { randomUuid } from './utils/string';
/**
* api请求
*/
class Api {
/**
* url
*/
url: string;
/**
*
*/
method: string;
2023-12-06 09:23:23 +08:00
/**
*
* param1: param请求参数
*/
beforeHandler: Function;
static abortControllers: Map<string, AbortController> = new Map();
constructor(url: string, method: string) {
this.url = url;
this.method = method;
}
2023-12-06 09:23:23 +08:00
/**
*
* @param func
* @returns this
*/
withBeforeHandler(func: Function) {
this.beforeHandler = func;
return this;
}
/**
* url
*/
getUrl() {
return request.getApiUrl(this.url);
}
/**
* api
* @param {Object} param api的参数
*/
request(param: any = null, options: any = {}): Promise<any> {
2023-12-06 09:23:23 +08:00
if (this.beforeHandler) {
this.beforeHandler(param);
}
return request.request(this.method, this.url, param, options);
}
/**
* , 使Api.cancelReq(key)
* @param key key关联的请求
* @param {Object} param api的参数
*/
allowCancelReq(key: string, param: any = null, options: RequestInit = {}): Promise<any> {
let controller = Api.abortControllers.get(key);
if (!controller) {
controller = new AbortController();
Api.abortControllers.set(key, controller);
}
options.signal = controller.signal;
return this.request(param, options);
}
/** 静态方法 **/
/**
*
* @param key key
*/
static cancelReq(key: string) {
let controller = Api.abortControllers.get(key);
if (controller) {
controller.abort();
Api.removeAbortKey(key);
}
}
static removeAbortKey(key: string) {
if (key) {
console.log('remove abort key: ', key);
Api.abortControllers.delete(key);
}
}
/**
* key生成新的abort keykey未取消
* @param oldKey key
* @returns key
*/
static genAbortKey(oldKey: string) {
if (!oldKey) {
return randomUuid();
}
if (Api.abortControllers.get(oldKey)) {
return oldKey;
}
return randomUuid();
}
/**
* Api对象url与method属性
* @param url url
* @param method (get,post,put,delete...)
*/
static create(url: string, method: string): Api {
return new Api(url, method);
}
/**
* get api
* @param url url
*/
static newGet(url: string): Api {
return Api.create(url, 'get');
}
/**
* new post api
* @param url url
*/
static newPost(url: string): Api {
return Api.create(url, 'post');
}
/**
* new put api
* @param url url
*/
static newPut(url: string): Api {
return Api.create(url, 'put');
}
/**
* new delete api
* @param url url
*/
static newDelete(url: string): Api {
return Api.create(url, 'delete');
}
}
export default Api;