2017-06-05 14:53:49 -05:00
|
|
|
import * as retry from 'async/retry'
|
2017-11-16 08:22:39 -06:00
|
|
|
import * as Bluebird from 'bluebird'
|
2017-05-15 15:22:03 -05:00
|
|
|
import { logger } from './logger'
|
2017-01-17 13:38:45 -06:00
|
|
|
|
2017-06-10 15:15:25 -05:00
|
|
|
type RetryTransactionWrapperOptions = { errorMessage: string, arguments?: any[] }
|
2017-11-21 06:43:29 -06:00
|
|
|
function retryTransactionWrapper <T> (
|
|
|
|
functionToRetry: (...args) => Promise<T> | Bluebird<T>,
|
|
|
|
options: RetryTransactionWrapperOptions
|
|
|
|
): Promise<T> {
|
2017-01-15 12:53:11 -06:00
|
|
|
const args = options.arguments ? options.arguments : []
|
|
|
|
|
2017-11-21 06:43:29 -06:00
|
|
|
return transactionRetryer<T>(callback => {
|
2017-07-11 10:04:57 -05:00
|
|
|
functionToRetry.apply(this, args)
|
2017-11-21 06:43:29 -06:00
|
|
|
.then((result: T) => callback(null, result))
|
2017-07-05 06:26:25 -05:00
|
|
|
.catch(err => callback(err))
|
2017-07-11 10:04:57 -05:00
|
|
|
})
|
2017-07-05 06:26:25 -05:00
|
|
|
.catch(err => {
|
2017-07-07 11:26:12 -05:00
|
|
|
logger.error(options.errorMessage, err)
|
2017-11-16 08:22:39 -06:00
|
|
|
throw err
|
2017-07-05 06:26:25 -05:00
|
|
|
})
|
2017-01-15 12:53:11 -06:00
|
|
|
}
|
|
|
|
|
2017-11-21 06:43:29 -06:00
|
|
|
function transactionRetryer <T> (func: (err: any, data: T) => any) {
|
|
|
|
return new Promise<T>((res, rej) => {
|
2017-07-05 06:26:25 -05:00
|
|
|
retry({
|
|
|
|
times: 5,
|
2017-01-15 12:53:11 -06:00
|
|
|
|
2017-07-11 10:04:57 -05:00
|
|
|
errorFilter: err => {
|
2017-07-05 06:26:25 -05:00
|
|
|
const willRetry = (err.name === 'SequelizeDatabaseError')
|
|
|
|
logger.debug('Maybe retrying the transaction function.', { willRetry })
|
|
|
|
return willRetry
|
|
|
|
}
|
2017-11-16 08:22:39 -06:00
|
|
|
}, func, (err, data) => err ? rej(err) : res(data))
|
2017-01-15 12:53:11 -06:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
2017-05-15 15:22:03 -05:00
|
|
|
export {
|
|
|
|
retryTransactionWrapper,
|
|
|
|
transactionRetryer
|
|
|
|
}
|