0.0.3 • Published 2 years ago
@obvcloud/request v0.0.3
@obvcloud/request
Install
$ pnpm install
$ npm run dev
$ npm run build
Usage
- 在请求文件中,例如
src/service/api/request.ts
文件中定义RequestInstance
实例 RequestInstance配置项如下:
参数 | 说明 | 类型 | 默认值 | 是否必填 |
---|---|---|---|---|
axiosConfig | 请求基础配置 | axios 框架下AxiosRequestConfig | 无默认值,{baseURL:''} | 必填 |
updateTokenCodes | 响应数据中对应更新token 的 code | (string | number)[] | 66666 | 非必填 |
updateTokenFunction | 用于更新token的回调方法 | function | undefined,可参考下面的示例代码 | 非必填 |
backendConfig | 响应数据格式 | object | {codeKey: 'code',dataKey: 'data',msgKey: 'message',successCode: 200} | 非必填 |
isBigInt | 是否将响应数据中的bigint进行处理 转换为string | boolean | false | 非必填 |
示例代码如下:
import { RequestInstance } from '@obvcloud/request';
export async function handleRefreshToken(axiosConfig: AxiosRequestConfig) {
const { resetAuthStore } = useAuthStore();
const refreshToken = localStg.get('refreshToken') || '';
const { data } = await fetchUpdateToken(refreshToken);
if (data) {
localStg.set('token', data.token);
localStg.set('refreshToken', data.refreshToken);
const config = { ...axiosConfig };
if (config.headers) {
config.headers.Authorization = data.token;
}
return config;
}
resetAuthStore();
return null;
}
// 初始化请求对象,设置更新 token 的函数
const { url } = getServiceEnvConfig(import.meta.env);
export const request = new RequestInstance({ baseURL: url }, undefined, handleRefreshToken);
- 在接口文件中,例如
src/service/api/user.ts
文件中使用request
实例(此文件可以通过 openapi-sdk 生成)
post代码实例
import { request } from './src/service';
export async function postPostWithFormData(body: {
/** 名称 */
name?: string;
/** 角色,来源:字典接口 type=role时获取 */
role?: string;
}) {
const formData = new FormData();
Object.keys(body).forEach((ele) => {
const item = (body as any)[ele];
if (item !== undefined && item !== null) {
if (typeof item === 'object' && !(item instanceof File)) {
if (item instanceof Array) {
item.forEach((f) => formData.append(ele, f || ''));
} else {
formData.append(ele, JSON.stringify(item));
}
} else {
formData.append(ele, item);
}
}
});
return request.post<API.RespPostWithJson>('/system/test/postWithFormData', formData, {
method: 'POST',
data: formData
});
}
get代码实例:
import { request } from './src/service';
export async function getGetWithParam(
// 叠加生成的Param类型 (非body参数swagger默认没有生成对象)
params: API.getGetWithParamParams
) {
return request.get<API.RespPostWithJson>('/system/test/getWithParam', undefined, {
method: 'GET',
params: {
...params
}
});
}
- 调用接口返回数据code不为200需要进行处理时,响应数据中的StatusCode需返回200请求,才可以得到响应数据中的code进行业务处理.例如如下数据:
{
"code": 1200,
"message": "success",
"success": true,
"data": {
}
}
如需要获得1200,则返回响应的response的StatusCode要设置200
请求配置
Options
TODO
LICENSE
MIT