]>
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(callback => { | |
12 | functionToRetry.apply(this, args) | |
13 | .then(result => callback(null, result)) | |
14 | .catch(err => callback(err)) | |
15 | }) | |
16 | .catch(err => { | |
17 | // Do not throw the error, continue the process | |
18 | logger.error(options.errorMessage, err) | |
19 | }) | |
20 | } | |
21 | ||
22 | function transactionRetryer (func: Function) { | |
23 | return new Promise((res, rej) => { | |
24 | retry({ | |
25 | times: 5, | |
26 | ||
27 | errorFilter: err => { | |
28 | const willRetry = (err.name === 'SequelizeDatabaseError') | |
29 | logger.debug('Maybe retrying the transaction function.', { willRetry }) | |
30 | return willRetry | |
31 | } | |
32 | }, func, err => err ? rej(err) : res()) | |
33 | }) | |
34 | } | |
35 | ||
36 | // --------------------------------------------------------------------------- | |
37 | ||
38 | export { | |
39 | retryTransactionWrapper, | |
40 | transactionRetryer | |
41 | } |