2017-05-15 22:22:03 +02:00
|
|
|
// TODO: import from ES6 when retry typing file will include errorFilter function
|
2017-06-05 21:53:49 +02:00
|
|
|
import * as retry from 'async/retry'
|
2017-07-05 13:26:25 +02:00
|
|
|
import * as Promise from 'bluebird'
|
2017-01-15 19:53:11 +01:00
|
|
|
|
2017-05-15 22:22:03 +02:00
|
|
|
import { logger } from './logger'
|
2017-01-17 20:38:45 +01:00
|
|
|
|
2017-06-10 22:15:25 +02:00
|
|
|
type RetryTransactionWrapperOptions = { errorMessage: string, arguments?: any[] }
|
2017-07-05 13:26:25 +02:00
|
|
|
function retryTransactionWrapper (functionToRetry: (... args) => Promise<any>, options: RetryTransactionWrapperOptions) {
|
2017-01-15 19:53:11 +01:00
|
|
|
const args = options.arguments ? options.arguments : []
|
|
|
|
|
2017-07-05 13:26:25 +02:00
|
|
|
return transactionRetryer(
|
2017-01-15 19:53:11 +01:00
|
|
|
function (callback) {
|
2017-07-05 13:26:25 +02:00
|
|
|
functionToRetry.apply(this, args)
|
|
|
|
.then(result => callback(null, result))
|
|
|
|
.catch(err => callback(err))
|
2017-01-15 19:53:11 +01:00
|
|
|
}
|
|
|
|
)
|
2017-07-05 13:26:25 +02:00
|
|
|
.catch(err => {
|
|
|
|
// Do not throw the error, continue the process
|
2017-07-07 18:26:12 +02:00
|
|
|
logger.error(options.errorMessage, err)
|
2017-07-05 13:26:25 +02:00
|
|
|
})
|
2017-01-15 19:53:11 +01:00
|
|
|
}
|
|
|
|
|
2017-07-05 13:26:25 +02:00
|
|
|
function transactionRetryer (func: Function) {
|
|
|
|
return new Promise((res, rej) => {
|
|
|
|
retry({
|
|
|
|
times: 5,
|
2017-01-15 19:53:11 +01:00
|
|
|
|
2017-07-05 13:26:25 +02:00
|
|
|
errorFilter: function (err) {
|
|
|
|
const willRetry = (err.name === 'SequelizeDatabaseError')
|
|
|
|
logger.debug('Maybe retrying the transaction function.', { willRetry })
|
|
|
|
return willRetry
|
|
|
|
}
|
|
|
|
}, func, function (err) {
|
|
|
|
err ? rej(err) : res()
|
|
|
|
})
|
2017-01-15 19:53:11 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
2017-05-15 22:22:03 +02:00
|
|
|
export {
|
|
|
|
retryTransactionWrapper,
|
|
|
|
transactionRetryer
|
|
|
|
}
|