]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/utils.js
Client: fix lint
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.js
CommitLineData
9f10b292 1'use strict'
8c308c2b 2
cbe2f7c3 3const crypto = require('crypto')
ed04d94f 4const retry = require('async/retry')
cbe2f7c3 5
f0f5567b 6const logger = require('./logger')
8c308c2b 7
f0f5567b 8const utils = {
a6fd2b30 9 badRequest,
c4403b29 10 cleanForExit,
441b66f8 11 generateRandomString,
55fa55a9 12 isTestInstance,
ed04d94f 13 getFormatedObjects,
d6a5b018 14 retryWrapper,
ed04d94f 15 transactionRetryer
cbe2f7c3
C
16}
17
a6fd2b30
C
18function badRequest (req, res, next) {
19 res.type('json').status(400).end()
20}
21
cbe2f7c3
C
22function generateRandomString (size, callback) {
23 crypto.pseudoRandomBytes(size, function (err, raw) {
24 if (err) return callback(err)
25
26 callback(null, raw.toString('hex'))
27 })
9f10b292 28}
8c308c2b 29
bc503c2a 30function cleanForExit (webtorrentProcess) {
9f10b292 31 logger.info('Gracefully exiting.')
bc503c2a 32 process.kill(-webtorrentProcess.pid)
9f10b292 33}
0ae2e7f7 34
441b66f8
C
35function isTestInstance () {
36 return (process.env.NODE_ENV === 'test')
37}
38
55fa55a9
C
39function getFormatedObjects (objects, objectsTotal) {
40 const formatedObjects = []
41
42 objects.forEach(function (object) {
43 formatedObjects.push(object.toFormatedJSON())
44 })
45
46 return {
47 total: objectsTotal,
48 data: formatedObjects
49 }
50}
51
d6a5b018
C
52// { arguments, errorMessage }
53function retryWrapper (functionToRetry, options, finalCallback) {
54 const args = options.arguments ? options.arguments : []
55
56 utils.transactionRetryer(
57 function (callback) {
58 return functionToRetry.apply(this, args.concat([ callback ]))
59 },
60 function (err) {
61 if (err) {
62 logger.error(options.errorMessage, { error: err })
63 }
64
65 // Do not return the error, continue the process
66 return finalCallback(null)
67 }
68 )
69}
70
ed04d94f
C
71function transactionRetryer (func, callback) {
72 retry({
73 times: 5,
74
75 errorFilter: function (err) {
76 const willRetry = (err.name === 'SequelizeDatabaseError')
77 logger.debug('Maybe retrying the transaction function.', { willRetry })
78 return willRetry
79 }
80 }, func, callback)
81}
82
9f10b292 83// ---------------------------------------------------------------------------
c45f7f84 84
9f10b292 85module.exports = utils