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