Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
@mxssfd/axios-wrapper
Advanced tools
Readme
request-template
基于状态处理实现的 axios 请求封装
pnpm add @mxssfd/axios-wrapper
首先定义一个封装模板
import { StatusHandlers, CustomConfig, HttpStatus, AxiosWrapper } from '@mxssfd/AxiosWrapper';
// 通用错误Handler
const errorHandler: StatusHandler<CustomConfig> = (res, data, customConfig) => {
if (!customConfig.silent) {
// ElMessage({ type: 'error', message: data.msg })
console.log('非静音模式,显示错误信息');
}
// throw data.data || new Error( `data: ${JSON.stringify(data)}`);
return Promise.reject(customConfig.returnRes ? res : data);
};
const statusHandlers: StatusHandlers = {
// 登录过期
[HttpStatus.UNAUTHORIZED]: (res, data, customConfig) => {
if (res.status === HttpStatus.UNAUTHORIZED) {
// Store.clearUser();
console.log('清理掉保存的用户信息');
Token.clear();
}
return errorHandler(res, data, customConfig);
},
// token更新了
207: (res, data, customConfig) => {
data.data.token && Token.set(data.data.token);
return customConfig.returnRes ? res : data;
},
// 成功
[HttpStatus.OK]: (res, data, customConfig) => {
return customConfig.returnRes ? res : data;
},
// 其余所有都提示失败
default: errorHandler,
};
直接使用 AxiosWrapper
const req = new AxiosWrapper<CustomConfig>({ baseURL: '/' }, { statusHandlers });
// 使用methodFactory生成请求方法
const get = req.methodFactory('get');
const post = req.methodFactory('post');
或者继承 AxiosWrapper 作为一个固定模板(推荐)
/**
* 主域名请求类
*/
export default class PrimaryRequest extends AxiosWrapper {
static readonly ins = new PrimaryRequest();
static readonly get = PrimaryRequest.ins.methodFactory('get');
static readonly post = PrimaryRequest.ins.methodFactory('post');
private constructor() {
super({ baseURL: import.meta.env.VITE_BASE_URL }, { statusHandlers });
}
protected setInterceptors() {
this.interceptors.request.use((config) => {
if (!config.headers) config.headers = {};
const headers = config.headers as AxiosRequestHeaders;
Token.exists() && (headers.authorization = `Bearer ${Token.get()}`);
// headers.uuid = getUUID();
return config;
});
}
}
最好再封装成 API
const { post, get } = PrimaryRequest;
export class User {
username!: string;
id!: number;
static login(data: { username: string; password: string }) {
return post<{ token: string }>('/user/login', data);
}
static getSelf() {
const req = get<{ user: User }>('/user/self', {}, { silent: true });
const cancel = PrimaryRequest.ins.cancelCurrentRequest;
setTimeout(() => cancel('cancel test'));
return req;
}
}
缓存并不是取消上一次的请求,而是不执行这一次的请求直接使用上一次缓存的结果
默认 5 秒内使用缓存
const { post } = PrimaryRequest;
export function login(data: { username: string; password: string }) {
// 5秒内都会是同样的数据
return post<{ token: string }>('/user/login', data, { useCache: true });
}
自定义过期时间
const { post } = PrimaryRequest;
export function login(data: { username: string; password: string }) {
// timeout单位为毫秒
return post<{ token: string }>('/user/login', data, { useCache: { timeout: 30 * 60 * 1000 } });
}
const req = login({ username: 'test', password: 'test' });
PrimaryRequest.ins.cancelCurrentRequest('test');
// 或者
PrimaryRequest.ins.cancelAll('test');
try {
await req;
} catch (e: { message: string }) {
// 会捕获该报错
// message: "test"
}
FAQs
axios封装类库
We found that @mxssfd/axios-wrapper demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.