]>
Commit | Line | Data |
---|---|---|
9f10b292 | 1 | 'use strict' |
8c308c2b | 2 | |
cbe2f7c3 | 3 | const crypto = require('crypto') |
ed04d94f | 4 | const retry = require('async/retry') |
cbe2f7c3 | 5 | |
f0f5567b | 6 | const logger = require('./logger') |
8c308c2b | 7 | |
f0f5567b | 8 | const 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 |
18 | function badRequest (req, res, next) { |
19 | res.type('json').status(400).end() | |
20 | } | |
21 | ||
cbe2f7c3 C |
22 | function 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 | 30 | function cleanForExit (webtorrentProcess) { |
9f10b292 | 31 | logger.info('Gracefully exiting.') |
bc503c2a | 32 | process.kill(-webtorrentProcess.pid) |
9f10b292 | 33 | } |
0ae2e7f7 | 34 | |
441b66f8 C |
35 | function isTestInstance () { |
36 | return (process.env.NODE_ENV === 'test') | |
37 | } | |
38 | ||
55fa55a9 C |
39 | function 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 } |
53 | function 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 |
71 | function 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 | 85 | module.exports = utils |