0.0.3 • Published 2 years ago

@obvcloud/request v0.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

@obvcloud/request

NPM version NPM downloads

Install

$ pnpm install
$ npm run dev
$ npm run build

Usage

  1. 在请求文件中,例如 src/service/api/request.ts 文件中定义 RequestInstance 实例 RequestInstance配置项如下:
参数说明类型默认值是否必填
axiosConfig请求基础配置axios 框架下AxiosRequestConfig无默认值,{baseURL:''}必填
updateTokenCodes响应数据中对应更新token 的 code(string | number)[]66666非必填
updateTokenFunction用于更新token的回调方法functionundefined,可参考下面的示例代码非必填
backendConfig响应数据格式object{codeKey: 'code',dataKey: 'data',msgKey: 'message',successCode: 200}非必填
isBigInt是否将响应数据中的bigint进行处理 转换为stringbooleanfalse非必填

示例代码如下:

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);
  1. 在接口文件中,例如 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
		}
	});
}
  1. 调用接口返回数据code不为200需要进行处理时,响应数据中的StatusCode需返回200请求,才可以得到响应数据中的code进行业务处理.例如如下数据:
{
	"code": 1200,
	"message": "success",
	"success": true,
	"data": {
	}
}

如需要获得1200,则返回响应的response的StatusCode要设置200

请求配置

Options

TODO

LICENSE

MIT