Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikermcneil/8252ce4b7f15d9e2901003a3a7a800cf to your computer and use it in GitHub Desktop.
Save mikermcneil/8252ce4b7f15d9e2901003a3a7a800cf to your computer and use it in GitHub Desktop.
example of iterator for the `where` clause from the `criteria` query key of a stage 2 query in waterline 0.13 / sails v1 (also works for stage 3 queries)
// ====================================================================================
// Example of iterating over the `where` clause from a stage 2 query from Waterline.
// (the example below attempts to demonstrate a few of the most useful guarantees)
//
// > Mostly pay attention to the structure. Other than that, you can safely assume
// > that, in short, everything is valid (+in a schema-aware way), guaranteed.
// ====================================================================================
/* ~%° before iterating */
(function _iterateRecursive(branch) {
// ╔═╗╦═╗╔═╗╔╦╗╦╔═╗╔═╗╔╦╗╔═╗
// ╠═╝╠╦╝║╣ ║║║║ ╠═╣ ║ ║╣
// ╩ ╩╚═╚═╝═╩╝╩╚═╝╩ ╩ ╩ ╚═╝
// If this branch contains a predicate...
if (branch.and || branch.or) {
/* ~%° before AND/OR */
_.each(whereClause.and || whereClause.or, function (conjunctOrDisjunct){
/* ~%° before conjunct/disjunct */
// Take the recursive step.
_iterateRecursive(conjunctOrDisjunct);
/* ~%° after conjunct/disjunct */
});
/* ~%° after AND/OR */
return;
}//-•
// ╔═╗╔═╗╔╗╔╔═╗╔╦╗╦═╗╔═╗╦╔╗╔╔╦╗
// ║ ║ ║║║║╚═╗ ║ ╠╦╝╠═╣║║║║ ║
// ╚═╝╚═╝╝╚╝╚═╝ ╩ ╩╚═╩ ╩╩╝╚╝ ╩
// Otherwise IWMIH, this branch contains a constraint.
// Figure out what we're filtering by.
// (e.g. "emailAddress")
var filterBy = _.keys(branch)[0];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ^^ note how we can trust that there's exactly one key
// (that's b/c any extra modifiers have been expanded into
// an `and` predicate via the "fracturing" process in Waterline
// core)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Now examine the constraint itself.
// `constraint` is either:
// • a dictionary (a "complex constraint")
// • or a primitive (an "eq constraint").
var constraint = branch[filterBy];
/* ~%° before constraint */
// If it is a complex constraint...
if (_.isObject(constraint)) {
/* ~%° on complex constraint (will always have exactly ONE key) */
}
// Otherwise it is an eq constraint.
else {
/* ~%° on eq constraint */
}
/* ~%° after constraint */
})(someCriteria.where);
/* ~%° after iterating */
@mikermcneil
Copy link
Author

Note that this example is also equally valid for iterating over the where clause of the criteria QK of a stage 3 query (i.e. in an adapter)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment