forked from AubaidFarrukh/smart-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
75 lines (61 loc) · 1.67 KB
/
Copy pathutils.ts
File metadata and controls
75 lines (61 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/** @format */
import { randomUUID } from 'crypto';
export function generateId(): string {
return randomUUID();
}
export function calculateDelay(
baseDelay: number,
attempt: number,
backoff: 'exponential' | 'linear' | 'none'
): number {
switch (backoff) {
case 'exponential':
return baseDelay * Math.pow(2, attempt - 1);
case 'linear':
return baseDelay * attempt;
case 'none':
return baseDelay;
default:
return baseDelay;
}
}
const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);
export function isIdempotentMethod(method?: string): boolean {
if (!method) return true;
return IDEMPOTENT_METHODS.has(method.toUpperCase());
}
export function defaultShouldRetry(error: any, allowNonIdempotent = false): boolean {
if (!error) return false;
if (!allowNonIdempotent && !isIdempotentMethod(error.config?.method)) {
return false;
}
if (
error.code === 'ECONNREFUSED' ||
error.code === 'ETIMEDOUT' ||
error.code === 'ENOTFOUND' ||
error.code === 'ECONNRESET'
) {
return true;
}
const status = error.response?.status;
if (!status) return false;
if (status === 408 || status === 429 || (status >= 500 && status < 600)) {
return true;
}
return false;
}
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export function getErrorMessage(error: any): string {
if (error.response?.statusText) {
return error.response.statusText;
}
if (error.message) {
return error.message;
}
return String(error);
}
export function getStatusCode(error: any): number | undefined {
return error.response?.status;
}