2017-06-05 21:53:49 +02:00
|
|
|
import * as retry from 'async/retry'
|
2017-11-16 15:22:39 +01:00
|
|
|
import * as Bluebird from 'bluebird'
|
2018-01-04 14:04:02 +01:00
|
|
|
import { Model } from 'sequelize-typescript'
|
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-11-21 13:43:29 +01:00
|
|
|
function retryTransactionWrapper <T> (
|
|
|
|
functionToRetry: (...args) => Promise<T> | Bluebird<T>,
|
|
|
|
options: RetryTransactionWrapperOptions
|
|
|
|
): Promise<T> {
|
2017-01-15 19:53:11 +01:00
|
|
|
const args = options.arguments ? options.arguments : []
|
|
|
|
|
2017-11-21 13:43:29 +01:00
|
|
|
return transactionRetryer<T>(callback => {
|
2017-07-11 17:04:57 +02:00
|
|
|
functionToRetry.apply(this, args)
|
2017-11-21 13:43:29 +01:00
|
|
|
.then((result: T) => callback(null, result))
|
2017-07-05 13:26:25 +02:00
|
|
|
.catch(err => callback(err))
|
2017-07-11 17:04:57 +02:00
|
|
|
})
|
2017-07-05 13:26:25 +02:00
|
|
|
.catch(err => {
|
2018-03-26 15:54:13 +02:00
|
|
|
logger.error(options.errorMessage, { err })
|
2017-11-16 15:22:39 +01:00
|
|
|
throw err
|
2017-07-05 13:26:25 +02:00
|
|
|
})
|
2017-01-15 19:53:11 +01:00
|
|
|
}
|
|
|
|
|
2017-11-21 13:43:29 +01:00
|
|
|
function transactionRetryer <T> (func: (err: any, data: T) => any) {
|
|
|
|
return new Promise<T>((res, rej) => {
|
2017-07-05 13:26:25 +02:00
|
|
|
retry({
|
|
|
|
times: 5,
|
2017-01-15 19:53:11 +01:00
|
|
|
|
2017-07-11 17:04:57 +02:00
|
|
|
errorFilter: err => {
|
2017-07-05 13:26:25 +02:00
|
|
|
const willRetry = (err.name === 'SequelizeDatabaseError')
|
|
|
|
logger.debug('Maybe retrying the transaction function.', { willRetry })
|
|
|
|
return willRetry
|
|
|
|
}
|
2017-11-16 15:22:39 +01:00
|
|
|
}, func, (err, data) => err ? rej(err) : res(data))
|
2017-01-15 19:53:11 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-03-13 16:00:39 +01:00
|
|
|
function updateInstanceWithAnother <T extends Model<T>> (instanceToUpdate: Model<T>, baseInstance: Model<T>) {
|
2018-01-04 14:04:02 +01:00
|
|
|
const obj = baseInstance.toJSON()
|
|
|
|
|
|
|
|
for (const key of Object.keys(obj)) {
|
|
|
|
instanceToUpdate.set(key, obj[key])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-15 19:53:11 +01:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
2017-05-15 22:22:03 +02:00
|
|
|
export {
|
|
|
|
retryTransactionWrapper,
|
2018-01-04 14:04:02 +01:00
|
|
|
transactionRetryer,
|
|
|
|
updateInstanceWithAnother
|
2017-05-15 22:22:03 +02:00
|
|
|
}
|