xk-request
v0.0.4
Published
```sh npm i xk-request ```
Readme
Basic Using
npm i xk-requestimport {fetchFunctionBatchGeneratorCurry, HRequest} from "xk-request";
/* 创建 HRequest 请求实例 */
const http = new HRequest({
baseURL: import.meta.env.VITE_APP_API,
timeout: 10000,
});
/* 基本请求 */
http.request(options)
/* 快捷请求 */
http.get<可传入响应类型>(url, options)
http.post(url, options)
http.delete(url, options)
http.patch(url, options)
http.put(url, options)
/* 示例 */
interface IResponse<T> {
code: number;
msg: string;
data: T;
}
http.get<IResponse<{name: string}>>("/user/info", {params: {id: "Uid001"}}).then((res) => {
if (res.code === 0) console.log(res.data.name);
});拦截器
1. 实例拦截器
import type {HInternalAxiosRequestConfig, HInternalAxiosResponseConfig} from "xk-request";
const http = new HRequest({
/* ... */
interceptors: {
/**
* requestInterceptor: 请求拦截器
* requestInterceptorCatch: 请求异常拦截器
* responseInterceptor: 响应拦截器
* responseInterceptorCatch: 响应异常拦截器
*/
requestInterceptor: (config: HInternalAxiosRequestConfig) => config,
responseInterceptor: (response: HInternalAxiosResponseConfig) => response
},
});
/* 示例 */
/** 请求拦截器 */
export function requestInterceptorHandle(config: HInternalAxiosRequestConfig): HInternalAxiosRequestConfig {
return config;
}
/** 响应拦截器 */
export function responseInterceptorHandle(response: HInternalAxiosResponseConfig): HInternalAxiosResponseConfig {
return response.data;
}
const http = new HRequest({
/* ... */
interceptors: {
requestInterceptor(config) {
return requestInterceptorHandle(config);
},
responseInterceptor(response) {
return responseInterceptorHandle(response);
},
}
})2. 请求拦截器: 在请求中的 options 中配置 interceptors 即可,具体与上面同理
/* 示例 */
http.get(url, {
interceptors: { /* 请求拦截器配置 */ }
})fetchFunctionBatchGeneratorCurry 工具函数
使用 fetchFunctionBatchGeneratorCurry 工具,可以通过配置的形式来快速生成对应的请求方法
import {fetchFunctionBatchGeneratorCurry, HRequest} from "xk-request";
const http = new HRequest({
/* ... */
});
const fetchFunctionBatchGenerator = fetchFunctionBatchGeneratorCurry(http); // 传入对应的 HRequest 请求实例,生成对应请求函数生成器
export {http, fetchFunctionBatchGenerator};使用
interface IUserFetch {
queryUserName: IUserNameResponse,
queryUserAge: IUserAgeResponse
}
interface IUserNameResponse { name: string }
interface IUserAgeResponse { age: number }
/**
* fetchFunctionBatchGenerator 生成函数可以通过传入泛型,来配置生成的请求与对应的响应类型
*/
const { queryUserName, queryUserAge } = fetchFunctionBatchGenerator<IUserFetch>([
/**
* 配置方式 1(元组类型): [key, url, method]
*/
["queryUserName", "/user/name", "GET"],
/**
* 配置方式 2(对象类型)
*/
{ key: "queryUserAge", url: "/user/age", method: "GET" }
]);
/**
* data: 请求参数(data 或 params - 内部自动转换)
* options: 其他配置
*/
queryUserName(data, options).then(res => { // res 的类型为 IUserNameResponse
console.log(res)
})
/**
* !!! 通过生成函数生成的请求函数的 options 扩展了一个 suffixUrl 配置参数,用来适配 `REST API` 风格的请求参数
* 如下: 最终发送的请求地址为 `/user/age/1`
*/
queryUserAge(data, { suffixUrl: '/1' })Tips
该文档写的比较简陋,暂时没有时间去维护、编写文档与测试该库,但上面基本使用都是有测过的...
