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

54 lines
1.5 KiB
TypeScript
Raw Normal View History

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