]>
Commit | Line | Data |
---|---|---|
1 | // TODO: import from ES6 when retry typing file will include errorFilter function | |
2 | import * as retry from 'async/retry' | |
3 | import * as Promise from 'bluebird' | |
4 | ||
5 | import { logger } from './logger' | |
6 | ||
7 | type RetryTransactionWrapperOptions = { errorMessage: string, arguments?: any[] } | |
8 | function retryTransactionWrapper (functionToRetry: (... args) => Promise<any>, options: RetryTransactionWrapperOptions) { | |
9 | const args = options.arguments ? options.arguments : [] | |
10 | ||
11 | return transactionRetryer( | |
12 | function (callback) { | |
13 | functionToRetry.apply(this, args) | |
14 | .then(result => callback(null, result)) | |
15 | .catch(err => callback(err)) | |
16 | } | |
17 | ) | |
18 | .catch(err => { | |
19 | // Do not throw the error, continue the process | |
20 | logger.error(options.errorMessage, err) | |
21 | }) | |
22 | } | |
23 | ||
24 | function transactionRetryer (func: Function) { | |
25 | return new Promise((res, rej) => { | |
26 | retry({ | |
27 | times: 5, | |
28 | ||
29 | errorFilter: function (err) { | |
30 | const willRetry = (err.name === 'SequelizeDatabaseError') | |
31 | logger.debug('Maybe retrying the transaction function.', { willRetry }) | |
32 | return willRetry | |
33 | } | |
34 | }, func, function (err) { | |
35 | err ? rej(err) : res() | |
36 | }) | |
37 | }) | |
38 | } | |
39 | ||
40 | // --------------------------------------------------------------------------- | |
41 | ||
42 | export { | |
43 | retryTransactionWrapper, | |
44 | transactionRetryer | |
45 | } |