使用装饰器
一、 @response()
1. 说明
使用 @response 时包裹请求时,业务代码不需要处理成功失败的弹窗处理,其余逻辑不影响。
被包裹的方法必须返回的是 promise 对象才可使用此装饰器。
2. 使用
import { response, retry } from '@gza/quantex-utils/es/decorators';
// 两种导入方式都可使用
import { decorators } from '@gza/quantex-utils';
const { response } = decorators;
class Store {
@response('添加成功')
addRole(formData) {
return this.api.put('/api/v2/roles/{id}', formData);
}
}
class RoleComponent {
// 采用async/await
handleAddRole = async () => {
let res = await this.store.addRole(formData);
// 关闭弹出框和刷新,如果上一步报错了,就不会执行如下两个方法了
this.search();
this.modal.close();
};
// 等价于
handleAddRole2 = async () => {
this.store.addRole(formData).then(() => {
this.search();
this.modal.close();
});
};
}
3. API
@response(msg: string)
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
msg | 成功时的提示信息 | string | - |
二、 @norepeat()
1. 说明
- 避免重复提交,被包裹的方法必须返回的是 promise 对象才可使用此装饰器
2. 原理
通过装饰器,在请求发起时,为请求方法的 this 对象增加一个标志位,当请求完成时此标志位会被释放,在请求完成前所有重复的请求都会被 reject('重复提交, 无效请求')
注意:使用 norepeat 包裹后的方法, 在被调用时, 必须有调用对象, 请注意以下例子说明
3. 使用
单个请求控制
import { decorators } from '@gza/quantex-utils';
const { norepeat } = decorators;
class Store {
@norepeat()
addRepoInstTemp(formData) {
return this.api.put('/api/v2/roles/{id}', formData);
}
}
class Index {
store = new Store();
// √ 正确调用, 必须有 this 调用对象, 此处的调用对象为 this.store
this.store.addRepoInstTemp(formData);
// X 错误调用
// const { addRepoInstTemp } = this.store;
// addRepoInstTemp(formData);
}
两个请求串行控制
import { decorators } from '@gza/quantex-utils';
const { norepeat } = decorators;
class Store {
// 串行请求
// 只控第一个发起的请求即可
addRepoInst() {
// √ 正确调用, 必须有 this 调用对象
this.checkSomething().then(() => {
this.addRepoInstTemp(inst);
});
// X 错误调用
// const { checkSomething } = this;
// checkSomething().then(() => {
// this.addRepoInstTemp(inst);
// });
}
// 第一个发起的请求
@norepeat()
checkSomething() {
return this.api.get('/api/v2/roles/get_role');
}
// 依赖第一个请求结束后才发起的请求
addRepoInstTemp(formData) {
return this.api.put('/api/v2/roles/{id}', formData);
}
}
三、 @retry()
1. 说明
使用装饰器 @retry(),当调用成功时,会返回 res 对象
当调用超时(状态码 408),将弹窗显示
重试
及稍后处理
被包裹的方法必须返回的是 promise 对象才可使用此装饰器
2. 使用
import { decorators } from '@gza/quantex-utils';
const { retry } = decorators;
class Store {
@retry()
addRepoInstTemp(formData) {
return this.api.put('/api/v2/roles/{id}', formData);
}
}
class RoleComponent {
addRepoInst = async formData => {
let res = await this.store.addRepoInstTemp(formData);
const result = alertForPKSException(res);
if (result) return;
// 正常处理
if (res.code === 200) {
const newFormData = Object.assign(formData, {
repoInstructionCode: res.data.code
});
this.addRepoInstOrder(newFormData);
} else {
// 给res增加一个方法ignoreRisk,点击【继续下单】按钮将调用该方法
res.ignoreRisk = ruleItemList => {
formData.ruleItemList = ruleItemList.map(rule => {
return rule.ruleItemID;
});
this.addRepoInst(formData);
};
}
if (res.code !== 200) {
alertForRisk({
ignoreRisk: formData.ruleItemList,
res,
sideBar: this.sideBar
});
}
};
}