UNPKG

forest-express-sequelize

Version:

Official Express/Sequelize Liana for Forest

86 lines (80 loc) 2.99 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); require("core-js/modules/es.array.iterator.js"); require("core-js/modules/es.regexp.exec.js"); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _lodash = _interopRequireDefault(require("lodash")); var _operators = _interopRequireDefault(require("../utils/operators")); /** * This helper class allows abstracting away the complexity * of using collection which have composite primary keys. */ class PrimaryKeysManager { constructor(model) { this._primaryKeys = _lodash.default.keys(model.primaryKeys); this._Sequelize = model.sequelize.constructor; } /** Build sequelize where condition from a list of packed recordIds */ getRecordsConditions(recordIds) { if (recordIds.length === 0) { return this._Sequelize.literal('(0=1)'); } switch (this._primaryKeys.length) { case 0: throw new Error('No primary key was found'); case 1: return this._getRecordsConditionsSimple(recordIds); default: return this._getRecordsConditionComposite(recordIds); } } /* Annotate records with their packed primary key */ annotateRecords(records) { var _this = this; if (this._primaryKeys.length > 1) { records.forEach(function (record) { record.forestCompositePrimary = _this._createCompositePrimary(record); }); } } _getRecordsConditionsSimple(recordIds) { return { [this._primaryKeys[0]]: recordIds.length === 1 ? recordIds[0] : recordIds }; } _getRecordsConditionComposite(recordIds) { var _this2 = this; const Ops = _operators.default.getInstance({ Sequelize: this._Sequelize }); return recordIds.length === 1 ? this._getRecordConditions(recordIds[0]) : { [Ops.OR]: recordIds.map(function (id) { return _this2._getRecordConditions(id); }) }; } /** Build sequelize where condition from a single packed recordId */ _getRecordConditions(recordId) { return _lodash.default.zipObject(this._primaryKeys, this._getPrimaryKeyValues(recordId)); } /** Create packed recordId from record */ _createCompositePrimary(record) { return this._primaryKeys.map(function (field) { return record[field] === null ? 'null' : record[field]; }).join(PrimaryKeysManager._GLUE); } /** Unpack recordId into an array */ _getPrimaryKeyValues(recordId) { // Prevent liana to crash when a composite primary keys is null, // this behaviour should be avoid instead of fixed. const unpacked = recordId.split(PrimaryKeysManager._GLUE).map(function (key) { return key === 'null' ? null : key; }); if (unpacked.length !== this._primaryKeys.length) { throw new Error('Invalid packed primary key'); } return unpacked; } } (0, _defineProperty2.default)(PrimaryKeysManager, "_GLUE", '|'); module.exports = PrimaryKeysManager;