All files / server/common utils.js

64.86% Statements 24/37
35.29% Branches 6/17
64.29% Functions 9/14
67.65% Lines 23/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61    2x 2x 2x   2x 6x 6x 6x     6x         2x             2x       2x 2x 2x   2x 2x     176x 176x 176x 176x 176x     176x         176x 176x                      
'use strict'
 
const crypto = require('crypto')
const fs = require('fs')
const base64url = require('base64url')
 
exports.generateToken = ({ length = 48, prefix = 'TCKT' }) =>
  new Promise((resolve, reject) => {
    crypto.randomBytes(length, (err, buffer) => {
      Iif (err) {
        reject(err)
      } else {
        resolve(prefix + '.' + base64url(buffer))
      }
    })
  })
 
exports.readFile = filename =>
  new Promise((resolve, reject) => {
    fs.readFile(filename, (err, data) => {
      resolve(err ? undefined : data)
    })
  })
 
exports.readJSON = filename =>
  exports.readFile(filename)
    .then(data => data ? JSON.parse(data) : undefined)
 
exports.promisifyClass = object => {
  const locals = {}
  return new Proxy(object, {
    set: (target, prop, value) => {
      locals[prop] = value
      return true
    },
    get: (target, prop, receiver) => {
      Iif (locals[prop]) return locals[prop]
      Iif (typeof object[prop] !== 'function') return object[prop]
      return (...args) => new Promise((resolve, reject) => {
        object[prop](...args, (err, ...results) => {
          Iif (err) {
            reject(err)
          } else {
            switch (results.length) {
              case 0:
                resolve()
                break
              case 1:
                resolve(results[0])
                break
              default:
                resolve(results)
                break
            }
          }
        })
      })
    }
  })
}