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

127 lines
2.6 KiB
TypeScript
Raw Normal View History

import request from './request';
import { useApiFetch } from './useRequest';
/**
* api请求
*/
class Api {
/**
* url
*/
url: string;
/**
*
*/
method: string;
2023-12-06 09:23:23 +08:00
/**
*
* param1: param请求参数
*/
beforeHandler: Function;
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 params params
* @param reqOptions
* @returns
*/
useApi<T>(params: any = null, reqOptions: RequestInit = {}) {
return useApiFetch<T>(this, params, reqOptions);
}
/**
* fetch api
* @param {Object} param api的参数
*/
async request(param: any = null, options: any = {}): Promise<any> {
const { execute, data } = this.useApi(param, options);
await execute();
return data.value;
}
/**
* xhr api
* @param {Object} param api的参数
*/
async xhrReq(param: any = null, options: any = {}): Promise<any> {
if (this.beforeHandler) {
this.beforeHandler(param);
}
return request.xhrReq(this.method, this.url, param, options);
}
/** 静态方法 **/
/**
* 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;
export class PageRes {
list: any[] = [];
total: number = 0;
}