-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
175 lines (157 loc) · 5.85 KB
/
mod.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { retried } from './deps.ts'
export interface InputOptions extends retried.OperationOptions {
/**
* Function invoked on each retry. Receives the error thrown by `input` as
* the first argument with properties `attemptNumber` and `retriesLeft`
* which indicate the current attempt number and the number of attempts
* left, respectively.
*
* ```ts
* import pRetried from 'https://deno.land/x/p_retried/mod.ts'
*
* async function run () => {
* const response = await fetch('https://sindresorhus.com/unicorn')
* if (!response.ok) {
* throw new Error(response.statusText)
* }
* return response.json()
* }
* }
*
* const result = await pRetried(run, {
* onFailedAttempt: error => {
* console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`);
* // 1st request => Attempt 1 failed. There are 4 retries left.
* // 2nd request => Attempt 2 failed. There are 3 retries left.
* // ...
* },
* retries: 5
* })
*
* console.log(result)
* ```
*
* The `onFailedAttempt` function can return a promise. For example, you can
* do some async logging:
*
* ```ts
* import pRetried from 'https://deno.land/x/p_retried/mod.ts'
* import { log } from './async-logger.ts'
* const run = async () => {
* // …
* }
*
* const result = await pRetried(run, {
* onFailedAttempt: async error => {
* await logger.log(error)
* }
* })
* ```
*
* If the `onFailedAttempt` function throws, all retries will be aborted and
* the original promise will reject with the thrown error.
*/
onFailedAttempt?: (error: RetryError) => void | Promise<void>
/** Number of tries to retry before rejecting */
retries?: number
}
interface Options extends retried.OperationOptions {
onFailedAttempt: (error: RetryError) => void | Promise<void>
retries: number
}
interface RetryError extends Error {
attemptNumber: number
retriesLeft: number
}
export class AbortError extends Error {
originalError: Error
/**
* Throwing an instance of the returned object will abort retrying and
* reject the promise.
*
* @param message The error message or an instance of a thrown `Error` / custom `Error`
*/
constructor(message: string | Error) {
super()
if (message instanceof Error) {
this.originalError = message
message = message.message
} else {
this.originalError = new Error(message)
this.originalError.stack = this.stack
}
this.name = "AbortError"
this.message = message
}
}
const decorateErrorWithCounts = (error: Error, attemptNumber: number, { retries }: Options) => {
// Minus 1 from attemptNumber because the first attempt does not count as a retry
const retriesLeft = retries - (attemptNumber - 1)
const retryError = error as RetryError
retryError.attemptNumber = attemptNumber
retryError.retriesLeft = retriesLeft
return retryError
}
/**
* Returns a `Promise` that is fulfilled when calling `input` returns a
* fulfilled promise. If calling `input` returns a rejected promise, `input` is
* called again until the maximum number of retries is reached. It then rejects
* with the last rejection reason.
*
* It doesn't retry on `TypeError` as that's a user error. The only exclusion to
* this logic is when `TypeError` is thrown by `fetch`'s API with the message
* 'Failed to fetch', which indicates that a request was not successful due to a
* network error -
* https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
*
* However, beware that `fetch` may throw `TypeError` with different error
* messages on different platforms for similar situations. See whatwg/fetch#526
* (comment) -
* https://github.com/whatwg/fetch/issues/526#issuecomment-554604080.
*
* @param input Function to be called, will be passed a single parameter that is
* the attempt number. Is espected to return a `Promise` or any value.
*
* @param inputOptions Additional options passed to `retried` - https://github.com/khrj/retried
*/
export default function pRetried<T>(
input: (attempt: number) => Promise<T>,
inputOptions: InputOptions,
): Promise<T> {
return new Promise((resolve, reject) => {
const options: Options = {
onFailedAttempt: () => { },
retries: 10,
...inputOptions,
}
const operation = retried.operation(options)
operation.attempt(async attemptNumber => {
try {
resolve(await input(attemptNumber))
} catch (error) {
if (!(error instanceof Error)) {
reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`))
return
}
if (error instanceof AbortError) {
operation.stop()
reject(error.originalError)
} else if (error instanceof TypeError && error.message !== "Failed to fetch") {
operation.stop()
reject(error)
} else {
const retryError = decorateErrorWithCounts(error, attemptNumber, options)
try {
await options.onFailedAttempt(retryError)
} catch (error) {
reject(error)
return
}
if (!operation.retry(error)) {
reject(operation.getMainError())
}
}
}
})
})
}