UNPKG

nodebook-nbql

Version:

Filter query language for nodebook

104 lines (85 loc) 2.66 kB
// Knexify var _ = require('lodash'), resourceContext = require('./context'), processFilter, buildWhere, whereType; _.mixin(require('./lodash-stmt')); processFilter = function processFilter(filter, context) { var joins = [], addJoin, expandAlias, processProperty; addJoin = function addJoin(join) { if (joins.indexOf(join) === -1) { joins.push(join); } }; expandAlias = function expandAlias(property) { // expand property aliases into their proper paths if (context.propAliases && context.propAliases[property]) { property = context.propAliases[property]; } return property; }; processProperty = function processProperty(property) { var parts; property = expandAlias(property); // separate properties with '.' parts = property.split('.'); // if length is 1, only column name exists, add table name if (parts.length === 1) { property = context.name ? context.name + '.' + property : property; } // Collect relations back into an array. // note: lazy way for building joins and include params if (parts.length > 1) { addJoin(parts[0]); } return property; }; // loop through and process all the properties _.eachStatement(filter.statements, function (statement) { statement.prop = processProperty(statement.prop); }); filter.joins = joins; return filter; }; // detect where type whereType = function whereType(statement, index) { var whereFunc = 'andWhere'; if (index === 0) { whereFunc = 'where'; } else if (statement.func === 'or') { whereFunc = 'orWhere'; } if (statement.value === null) { if (statement.func === 'or') { whereFunc = statement.op === 'IS NOT' ? 'orWhereNotNull' : 'orWhereNull'; } else { whereFunc = statement.op === 'IS NOT' ? 'whereNotNull' : 'whereNull'; } } return whereFunc; }; // build where buildWhere = function buildWhere(qb, statements) { _.eachStatement( statements, function single(statement, index) { qb[whereType(statement, index)](statement.prop, statement.op, statement.value); }, function group(statement, index) { qb[whereType(statement, index)](function (_qb) { buildWhere(_qb, statement.group); }); } ); }; // knexify // converts a 'filter' from a set of statements from JSON to a set of 'where' calls on a queryBuilder object module.exports = function knexify(qb, filter) { filter = processFilter(filter, resourceContext[qb._single.table]); buildWhere(qb, filter.statements); return qb; }; // used only for testing module.exports._buildWhere = buildWhere;