crystelf-core/src/core/tools/tools.service.ts
2025-07-25 16:03:12 +08:00

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;
}
}