Dynamic Filtering for RethinkDB
/*
* DYNAMIC FILTERING FOR RETHINKDB
* Accepts an object with property values to match
* Array values will match any of
* filters = {name: 'Iron Man', identity: ['Tony Stark', 'Anthony Stark']};
*/
r.table('test').filter(function(row) {
// Create a placeholder for the predicates
var predicates = [];
// Define a function to recurse through filters
function makePredicates(obj, current_row) {
for (var prop in obj) {
var predicate = current_row(prop);
// This is a deeper object
if (!Array.isArray(obj[prop]) && typeof filters[prop] == 'object') {
makePredicates(obj[prop], predicate);
}
else {
// If an array value was passed in
if (Array.isArray(obj[prop])) {
predicate = r.expr(obj[prop]).contains(predicate);
}
else {
predicate = predicate.eq(obj[prop]);
}
}
// Add the predicate function to an array
predicates.push(predicate);
};
}
// Build predicates with the passed in filters
makePredicates(filters, row);
// Start building a predicate function chain
var filter_function = predicates[0];
// Chain the remaining predicate functions
predicates.slice(1).forEach(function(predicate) {
filter_function = filter_function.and(predicate);
});
return filter_function;
});