UNPKG

@userlab/dx

Version:

Build efficient GraphQL backend

60 lines (59 loc) 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.whereResolve = exports.getSqlCondition = void 0; var constants_1 = require("../constants"); var db_1 = require("../db"); var getSqlCondition = function (table, fields, condition) { if (!condition) return null; var field = Object.keys(condition)[0]; if (field === 'or' || field === 'and') { if (condition[field].length === 0) return ''; if (condition[field].length === 1) return exports.getSqlCondition(table, fields, condition[field][0]); var subconditions = condition[field]; var subsqls = subconditions.map(function (subcondition) { return exports.getSqlCondition(table, fields, subcondition); }); return "(" + subsqls.join(" " + field.toUpperCase() + " ") + ")"; } else { var key = fields[field].sqlColumn || field; var _field = fields[field]; if (_field && _field.sqlExpr && typeof _field.sqlExpr === 'function') { key = _field.sqlExpr(table, {}, null, null); } else { key = table + "." + key; } var operator = Object.keys(condition[field])[0]; var value = condition[field][operator]; // This is used when the user wants to filter the data by // location including the sublocations if (key === table + ".location_id" && operator === "insub") { return table + ".location_id IN (\n WITH RECURSIVE sublocation AS (\n SELECT l.id FROM location l WHERE l.id = '" + value + "'\n UNION\n SELECT l.id FROM location l INNER JOIN sublocation S ON S.id = l.location_id\n ) SELECT id FROM sublocation\n )"; } return key + " " + constants_1.operators[operator].sql + " " + db_1.getSqlValue(value); } }; exports.getSqlCondition = getSqlCondition; var whereResolve = function (_a) { var fields = _a.fields; return function (table, _a, _b) { var where = _a.where; var user = _b.user; var condition = exports.getSqlCondition(table, fields, where) || ''; // Filter by user location if (fields.locationId && (user === null || user === void 0 ? void 0 : user.locationId) && (user === null || user === void 0 ? void 0 : user.locations)) { var fieldName = table === "\"locations\"" ? "id" : "location_id"; if (condition) condition = condition + " AND"; condition = condition + " " + table + "." + fieldName + " IN (" + user.locations .map(function (locationId) { return "'" + locationId + "'"; }) .join(',') + ")"; } return condition; }; }; exports.whereResolve = whereResolve;