Created
September 12, 2013 08:06
-
-
Save kbanman/6534282 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Knex = require('knex'); | |
var _ = require('underscore'); | |
Knex.Initialize({ | |
client: 'mysql', | |
connection: { | |
host: 'localhost', | |
user: '', | |
database: '' | |
} | |
}); | |
var query = { | |
filters: [ | |
{ field: "company_id", op:"=", value:1234 }, | |
{ | |
group: "all", | |
filters: [ | |
{ field:"model", op:"=", value:"Customer" }, | |
{ field:"entity_id", op:"=", value:1234 } | |
] | |
}, | |
{ | |
group: "any", | |
filters: [ | |
{ field:"first_name", op:"like", value:"%john%" }, | |
{ field:"last_name", op:"like", value:"%smith%" } | |
] | |
} | |
] | |
}; | |
/* Expected result: | |
* | |
* WHERE ( | |
* company_id = 1234 | |
* AND ( | |
* model = 'Customer' | |
* AND entity_id = 1234 | |
* ) | |
* AND ( | |
* first_name LIKE '%john%' | |
* OR last_name LIKE '%smith' | |
* ) | |
* ) | |
*/ | |
function applyFilters(query, filters) { | |
var groupFilters = function(_filters, _group) { | |
var fn = _group == 'all' ? 'where' : 'orWhere'; | |
return function() { | |
var _query = this; | |
_filters.forEach(function(f, i) { | |
if (f.group) { | |
return _query[fn](groupFilters(f.filters, f.group)); | |
} | |
//if(queryableFields.indexOf(f.field) == -1) { | |
// return; | |
//} | |
return _query[fn](f.field, f.op, f.value); | |
}); | |
}; | |
}; | |
query.where(groupFilters(filters, 'all')); | |
} | |
var q = Knex('customers'); | |
applyFilters(q, query.filters); | |
console.log(q.toString()); | |
process.exit(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment