all files / lib/offshore/query/ criteria.js

89.19% Statements 33/37
79.31% Branches 23/29
100% Functions 6/6
88.57% Lines 31/35
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     32× 32×     32×     32×     32× 12×   20×     20×     16× 16× 16× 16× 16×   16×       563×     561×    
var _ = require('lodash');
var normalize = require('../utils/normalize');
 
var Criteria = module.exports = {
  toString: function(criteria) {
    var self = this;
    Iif (_.isUndefined(criteria)) {
      return 'undefined';
    }
    Iif (_.isNull(criteria)) {
      return 'null';
    }
    Iif (_.isString(criteria)) {
      return criteria;
    }
    if (_.isNumber(criteria) || _.isDate(criteria) || _.isBoolean(criteria)) {
      return criteria.toString();
    }
    Iif (_.isFunction(criteria)) {
      return 'fct()';
    }
    if (_.isArray(criteria)) {
      var arr = [];
      criteria.forEach(function(crit) {
        arr.push(self.toString(crit));
      });
      return '[' + _.sortBy(arr, function(ct) { return ct; }).toString() + ']';
    }
    Eif (_.isObject(criteria)) {
      var keys = _.sortBy(_.keys(criteria), function(key) { return key; });
      var ret = '{';
      keys.forEach(function(key){
        ret += "'" + key + "':" + self.toString(criteria[key]) + ',';
      });
      return ret.slice(0,-1) + '}';
    }
  },
  merge: function(destination, source) {
    if (source) {
      var dest = normalize.criteria(_.cloneDeep(destination));
      source = normalize.criteria(source);
      if (dest.where && source.where) {
        destination.where = { and: [dest.where, source.where]};
      } else Eif (dest.where || source.where) {
        destination.where = dest.where || source.where;
      }
      destination.sort = _.defaults({}, dest.sort, source.sort);
      return destination;
    }
    return destination;
  }
};