File: js/__improved-model/model-swtch/build-condition.js
/* jshint ignore:start */
if (typeof define !== 'function') { var define = require('amdefine')(module) }
/* jshint ignore:end */
define(function (require, exports, module) {
'use strict';
var objectQuery = require('object-query'),
_ = require('lodash');
var or = /\s*\|\|\s*/g,
and = /\s*&&\s*/g,
colon = /\s*:\s*/g,
pipe = /\s*\|\s*/g;
/**
* If criteria is a string, parses it.
* Otherwise, simply return the criteria object.
*
* @param {[type]} criteria [description]
* @return {[type]} [description]
*/
function parseCriteriaStr(criteriaStr) {
// examples:
// 'attrName:attrValue'
// 'attrName:maybeThis|orThat|orThatOther && anotherAttr:anotherVal || yetAnother:val'
// [1] split ORs
var ors = criteriaStr.split(or);
var possibilities = _.map(ors, function (criteriaStr) {
// criteriaStr: attr1:v1|v2|v3 && attr2:v4
var criteria = {};
_.each(criteriaStr.split(and), function (criteriaStr) {
// criteriaStr: value:someValue|orAnother
var split = criteriaStr.split(colon);
var key = split[0],
value = split[1].split(pipe);
if (!split[1]) {
throw new Error('No value found for ' + key + ' criterion.');
}
// if value is an array of a single item, unwrap it
criteria[key] = (value.length > 1) ? value : value[0];
});
return criteria;
});
return possibilities;
}
/**
* Returns a function that returns a boolean.
*
* @param {[type]} criteria [description]
* @return {[type]} [description]
*/
module.exports = function buildCondition(model, criteria) {
// parse out the criteria
if (_.isString(criteria)) {
criteria = parseCriteriaStr(criteria);
}
// return a partialized objectQuery that
// already has the model.
return _.partial(objectQuery(criteria), model.attributes);
};
});