Update systemd service template
[oweals/peertube.git] / server / helpers / utils.ts
1 import * as express from 'express'
2
3 import { pseudoRandomBytes } from 'crypto'
4
5 import { logger } from './logger'
6
7 function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) {
8   res.type('json').status(400).end()
9 }
10
11 function generateRandomString (size: number, callback: (err: Error, randomString?: string) => void) {
12   pseudoRandomBytes(size, function (err, raw) {
13     if (err) return callback(err)
14
15     callback(null, raw.toString('hex'))
16   })
17 }
18
19 function createEmptyCallback () {
20   return function (err) {
21     if (err) logger.error('Error in empty callback.', { error: err })
22   }
23 }
24
25 interface FormatableToJSON {
26   toFormatedJSON ()
27 }
28
29 function getFormatedObjects<U, T extends FormatableToJSON> (objects: T[], objectsTotal: number) {
30   const formatedObjects: U[] = []
31
32   objects.forEach(function (object) {
33     formatedObjects.push(object.toFormatedJSON())
34   })
35
36   return {
37     total: objectsTotal,
38     data: formatedObjects
39   }
40 }
41
42 // ---------------------------------------------------------------------------
43
44 export {
45   badRequest,
46   createEmptyCallback,
47   generateRandomString,
48   getFormatedObjects
49 }