1
0
Fork 0
peertube/server/helpers/database-utils.ts

41 lines
1.2 KiB
TypeScript
Raw Normal View History

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