Code

Code

URL query string parameter to mongoose parameters Raw


exports.query = function(query) {
  var operator = {};
  if (query) {

    var tokenize = function(operator, str) {
      var data = str.split(operator);
      if (data.length > 1) {
        return data;
      }
      return null;
    };

    var tokens = query.split(',');

    for (var i = 0; i < tokens.length; ++i) {
      var selector = tokenize('<=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$lte'] = selector[1];
        continue;
      }

      selector = tokenize('>=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$gte'] = selector[1];
        continue;
      }

      selector = tokenize('<', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$lt'] = selector[1];
        continue;
      }

      selector = tokenize('>', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$gt'] = selector[1];
        continue;
      }

      selector = tokenize('!=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$net'] = selector[1];
        continue;
      }

      selector = tokenize('=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]] = selector[1];
        continue;
      }

      selector = tokenize('$regex', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]] =  new RegExp(selector[1], 'i');
        continue;
      }
    }
  }

  return operator;
};