All files / server/utils knex.js

90.48% Statements 19/21
66.67% Branches 8/12
100% Functions 3/3
90.48% Lines 19/21
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            1x 1x   1x               1x 274x   274x 274x 1158x       274x 176x     274x       1158x       1158x     1158x     1158x 108x   108x 108x       1158x    
/**
 * Knex-related utilities.
 *
 * @module server/utils/knex
 * @see http://knexjs.org
 */
const _ = require('lodash');
const config = require('../../config');
 
const logger = config.logger('db');
 
/**
 * A logger function that can be passed to knex to log all database queries.
 *
 * @function
 * @param {*} query - A knex query.
 */
exports.logger = function(query) {
  let message = query.sql;
 
  Eif (query.bindings) {
    query.bindings.forEach((binding, i) => {
      message = message.replace(new RegExp(`\\$${i + 1}`), logValue(binding));
    });
  }
 
  if (!message.match(/;$/)) {
    message = message + ';';
  }
 
  logger.trace(message);
}
 
function logValue(value) {
  Iif (value === undefined) {
    return 'undefined';
  }
 
  Iif (value instanceof Buffer) {
    value = value.toString('hex');
  } else {
    value = JSON.stringify(value);
  }
 
  if (value.length > 50) {
    value = `${value.substring(0, 50)}...`;
 
    Eif (value.match(/^"/)) {
      value = `${value}"`;
    }
  }
 
  return value;
}