]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/database-utils.ts
Fix issues with truncated description and utf characters
[github/Chocobozzz/PeerTube.git] / server / helpers / database-utils.ts
1 import * as retry from 'async/retry'
2 import * as Bluebird from 'bluebird'
3 import { Model } from 'sequelize-typescript'
4 import { logger } from './logger'
5
6 type RetryTransactionWrapperOptions = { errorMessage: string, arguments?: any[] }
7 function retryTransactionWrapper <T> (
8 functionToRetry: (...args) => Promise<T> | Bluebird<T>,
9 options: RetryTransactionWrapperOptions
10 ): Promise<T> {
11 const args = options.arguments ? options.arguments : []
12
13 return transactionRetryer<T>(callback => {
14 functionToRetry.apply(this, args)
15 .then((result: T) => callback(null, result))
16 .catch(err => callback(err))
17 })
18 .catch(err => {
19 logger.error(options.errorMessage, err)
20 throw err
21 })
22 }
23
24 function transactionRetryer <T> (func: (err: any, data: T) => any) {
25 return new Promise<T>((res, rej) => {
26 retry({
27 times: 5,
28
29 errorFilter: err => {
30 const willRetry = (err.name === 'SequelizeDatabaseError')
31 logger.debug('Maybe retrying the transaction function.', { willRetry })
32 return willRetry
33 }
34 }, func, (err, data) => err ? rej(err) : res(data))
35 })
36 }
37
38 function updateInstanceWithAnother <T extends Model<T>> (instanceToUpdate: Model<T>, baseInstance: Model<T>) {
39 const obj = baseInstance.toJSON()
40
41 for (const key of Object.keys(obj)) {
42 instanceToUpdate.set(key, obj[key])
43 }
44 }
45
46 // ---------------------------------------------------------------------------
47
48 export {
49 retryTransactionWrapper,
50 transactionRetryer,
51 updateInstanceWithAnother
52 }