mirror of
https://github.com/crystelf/crystelf-core.git
synced 2025-10-14 05:19:19 +00:00
52 lines
1.2 KiB
TypeScript
52 lines
1.2 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { RetryOptions } from './retry-options.interface';
|
|
|
|
@Injectable()
|
|
export class ToolsService {
|
|
private readonly logger = new Logger(ToolsService.name);
|
|
|
|
/**
|
|
* 异步重试
|
|
* @param operation
|
|
* @param options
|
|
*/
|
|
async retry<T>(
|
|
operation: () => Promise<T>,
|
|
options: RetryOptions,
|
|
): Promise<T> {
|
|
let attempt = 0;
|
|
let lastError: any;
|
|
|
|
while (attempt < options.maxAttempts) {
|
|
try {
|
|
return await operation();
|
|
} catch (error) {
|
|
lastError = error;
|
|
attempt++;
|
|
|
|
if (attempt < options.maxAttempts) {
|
|
const delay = options.initialDelay * Math.pow(2, attempt - 1);
|
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
}
|
|
}
|
|
}
|
|
|
|
this.logger.error('重试失败', lastError);
|
|
throw lastError;
|
|
}
|
|
|
|
/**
|
|
* 从一个可迭代列表中随机选择一个对象
|
|
*/
|
|
getRandomItem<T>(list: T[]): T {
|
|
return list[Math.floor(Math.random() * list.length)];
|
|
}
|
|
|
|
/**
|
|
* 获取随机数
|
|
*/
|
|
getRandomDelay(min: number, max: number): number {
|
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
}
|
|
}
|