Skip to content

Commit

Permalink
feat(tag): 支持使用symbol作为tag
Browse files Browse the repository at this point in the history
  • Loading branch information
mengxinssfd committed Apr 29, 2022
1 parent 955db3a commit 4986b71
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
14 changes: 12 additions & 2 deletions __test__/AxiosRequestTemplate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,14 +240,19 @@ describe('AxiosRequestTemplate', () => {
]);
});
test('cancel with tag', async () => {
const req = new AxiosRequestTemplate(undefined, { tag: 'cancellable' });
const req = new AxiosRequestTemplate<CustomConfig>(undefined, { tag: 'cancellable' });
const get = req.methodFactory('get');
const res1 = get('/user', {}, { tag: 'irrevocable' });
const res2 = get('/user');
const res3 = get('/user');
const symbol = Symbol('cancel');
const symbol1 = Symbol('cancel');
const res4 = get('/user', {}, { tag: symbol });
const res5 = get('/user', {}, { tag: symbol1 });
req.cancelWithTag('cancellable', 'cancel with tag');
req.cancelWithTag(symbol, 'cancel with tag symbol');

const res = await Promise.allSettled([res1, res2, res3]);
const res = await Promise.allSettled([res1, res2, res3, res4, res5]);

expect(res).toEqual([
{
Expand All @@ -256,6 +261,11 @@ describe('AxiosRequestTemplate', () => {
},
{ status: 'rejected', reason: 'cancel with tag' },
{ status: 'rejected', reason: 'cancel with tag' },
{ status: 'rejected', reason: 'cancel with tag symbol' },
{
status: 'fulfilled',
value: { code: 200, data: { id: 1, username: 'get' }, msg: 'success' },
},
]);
req.cancelWithTag('default', 'cancel with tag');
});
Expand Down
4 changes: 2 additions & 2 deletions src/AxiosRequestTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class AxiosRequestTemplate<CC extends CustomConfig = CustomConfig> {

// cancel函数缓存
protected readonly cancelerSet = new Set<Canceler>();
protected readonly tagCancelMap = new Map<string, Canceler[]>();
protected readonly tagCancelMap = new Map<CustomConfig['tag'], Canceler[]>();

cancelCurrentRequest?: Canceler;

Expand Down Expand Up @@ -361,7 +361,7 @@ export class AxiosRequestTemplate<CC extends CustomConfig = CustomConfig> {
}

// 根据tag标签取消请求
cancelWithTag(tag: string, msg?: string) {
cancelWithTag(tag: CustomConfig['tag'], msg?: string) {
const cancelers = this.tagCancelMap.get(tag);
if (!cancelers) return;
cancelers.forEach((canceler) => {
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export interface CustomConfig {
// 缓存配置
cache?: boolean | CustomCacheConfig;
// 标签,用于取消请求
tag?: string;
tag?: string | symbol;
// 失败重试次数
retry?: number | RetryConfig;
}
Expand Down

0 comments on commit 4986b71

Please sign in to comment.