Coerce types for values of where clause
This commit is contained in:
parent
4c0c852c20
commit
2df0c4b21d
68
lib/dao.js
68
lib/dao.js
|
@ -351,6 +351,69 @@ DataAccessObject.all = function () {
|
|||
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
|
||||
* 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);
|
||||
if(params.where) {
|
||||
params.where = this.coerce(params.where);
|
||||
}
|
||||
if(near) {
|
||||
if(supportsGeo) {
|
||||
// convert it
|
||||
|
@ -511,6 +577,7 @@ DataAccessObject.destroyAll = function destroyAll(where, cb) {
|
|||
} else {
|
||||
// Support an optional where object
|
||||
where = removeUndefined(where);
|
||||
where = this.coerce(where);
|
||||
this.getDataSource().connector.destroyAll(this.modelName, where, function (err, data) {
|
||||
cb && cb(err, data);
|
||||
}.bind(this));
|
||||
|
@ -556,6 +623,7 @@ DataAccessObject.count = function (where, cb) {
|
|||
where = null;
|
||||
}
|
||||
where = removeUndefined(where);
|
||||
where = this.coerce(where);
|
||||
this.getDataSource().connector.count(this.modelName, cb, where);
|
||||
};
|
||||
|
||||
|
|
Loading…
Reference in New Issue