PeerTube/server/helpers/database-utils.ts

46 lines
1.3 KiB
TypeScript
Raw Normal View History

2017-05-15 15:22:03 -05:00
// TODO: import from ES6 when retry typing file will include errorFilter function
2017-06-05 14:53:49 -05:00
import * as retry from 'async/retry'
import * as Promise 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[] }
function retryTransactionWrapper (functionToRetry: (... args) => Promise<any>, options: RetryTransactionWrapperOptions) {
const args = options.arguments ? options.arguments : []
return transactionRetryer(
function (callback) {
functionToRetry.apply(this, args)
.then(result => callback(null, result))
.catch(err => callback(err))
}
)
.catch(err => {
// Do not throw the error, continue the process
logger.error(options.errorMessage, { error: err })
})
}
function transactionRetryer (func: Function) {
return new Promise((res, rej) => {
retry({
times: 5,
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-05-15 15:22:03 -05:00
export {
retryTransactionWrapper,
transactionRetryer
}