Coerce types for values of where clause

This commit is contained in:
Raymond Feng 2013-11-29 14:45:50 -08:00
parent 4c0c852c20
commit 2df0c4b21d
1 changed files with 68 additions and 0 deletions

View File

@ -351,6 +351,69 @@ DataAccessObject.all = function () {
DataAccessObject.find.apply(this, arguments); DataAccessObject.find.apply(this, arguments);
}; };
var operators = {
gt: '>',
gte: '>=',
lt: '<',
lte: '<=',
between: 'BETWEEN',
inq: 'IN',
nin: 'NOT IN',
neq: '!=',
like: 'LIKE',
nlike: 'NOT LIKE'
};
DataAccessObject.coerce = function (where) {
if (!where) {
return where;
}
var props = this.getDataSource().getModelDefinition(this.modelName).properties;
for (var p in where) {
var DataType = props[p] && props[p].type;
if (!DataType) {
continue;
}
if (Array.isArray(DataType) || DataType === Array) {
DataType = List;
} else if (DataType.name === 'Date') {
var OrigDate = Date;
DataType = function Date(arg) {
return new OrigDate(arg);
};
}
var val = where[p];
// Check there is an operator
var operator = null;
if ('object' === typeof val) {
for (var op in operators) {
if (op in val) {
val = val[op];
operator = op;
break;
}
}
}
// Coerce the array items
if (Array.isArray(val)) {
for (var i = 0; i < val.length; i++) {
val[i] = DataType(val[i]);
}
} else {
val = DataType(val);
}
// Rebuild {property: {operator: value}}
if (operator) {
var value = {};
value[operator] = val;
val = value;
}
where[p] = val;
}
return where;
};
/** /**
* Find all instances of Model, matched by query * Find all instances of Model, matched by query
* make sure you have marked as `index: true` fields for filter or sort * make sure you have marked as `index: true` fields for filter or sort
@ -389,6 +452,9 @@ DataAccessObject.find = function find(params, cb) {
} }
params = removeUndefined(params); params = removeUndefined(params);
if(params.where) {
params.where = this.coerce(params.where);
}
if(near) { if(near) {
if(supportsGeo) { if(supportsGeo) {
// convert it // convert it
@ -511,6 +577,7 @@ DataAccessObject.destroyAll = function destroyAll(where, cb) {
} else { } else {
// Support an optional where object // Support an optional where object
where = removeUndefined(where); where = removeUndefined(where);
where = this.coerce(where);
this.getDataSource().connector.destroyAll(this.modelName, where, function (err, data) { this.getDataSource().connector.destroyAll(this.modelName, where, function (err, data) {
cb && cb(err, data); cb && cb(err, data);
}.bind(this)); }.bind(this));
@ -556,6 +623,7 @@ DataAccessObject.count = function (where, cb) {
where = null; where = null;
} }
where = removeUndefined(where); where = removeUndefined(where);
where = this.coerce(where);
this.getDataSource().connector.count(this.modelName, cb, where); this.getDataSource().connector.count(this.modelName, cb, where);
}; };