From 10daa29abf6aab1bff078d9a11f7ec71d8aa1639 Mon Sep 17 00:00:00 2001 From: Sebastien P Date: Tue, 19 Jan 2021 16:47:48 +0100 Subject: [PATCH 1/2] push userRequest in smartfield context --- .DS_Store | Bin 0 -> 6148 bytes src/routes/associations.js | 3 ++- src/routes/resources.js | 5 ++++- src/serializers/resource.js | 4 +++- src/services/smart-fields-values-injector.js | 7 ++++--- 5 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..00d246e96b38b062183a9cd051cffc2b0ab9d2d6 GIT binary patch literal 6148 zcmeHKJxc>Y5S>j9Jq<_-3(G^WR0vpFoH70au@9F>5=e4Elm32+mG=Gw!NS5q1S>nW zwzc%l?&h-VC4z+_G6TEsZa#MA-eqsHM5OAIc8#b?L?H%au!?Dpu$@OiN>;NDRCO+FR^7NE?l$pC<4K zSB~!<)y?((SKjS!c#pbn75tr|0QGiI>)5Ms>*Ch6xi!7LKTK=NV+ZN1ig|V~?{1Ux zE>H7PmnM{W*{O6@^l)oyPfBLFafS_`gqj|N7p0LB(GgU~>f2?d%^WsexjghL-$zu01C z(1erHnX!(|tn3Lz>Fm%)+MQHvP-bC381NY=o7*b)|HH-Se?Lg>gaKjTUooJ9#!;h= zN3y-O@NnE~Ba9{n3;SgTbqFTgj`an%;tdQfutj_Uj4fscp@GOB0ZoHU!oaUG@Bt+~ Bs(Szc literal 0 HcmV?d00001 diff --git a/src/routes/associations.js b/src/routes/associations.js index 6bd7bfa3d..e5b915fa4 100644 --- a/src/routes/associations.js +++ b/src/routes/associations.js @@ -38,6 +38,7 @@ module.exports = function Associations(app, model, Implementation, integrator, o function getContext(request) { const association = getAssociation(request); const params = _.extend(request.query, request.params, association); + params.userRequest = request.user;//SPA const models = Implementation.getModels(); const associationField = getAssociationField(params.associationName); const associationModel = _.find(models, (refModel) => @@ -57,7 +58,7 @@ module.exports = function Associations(app, model, Implementation, integrator, o associationModel, records, integrator, - null, + {userRequest: request.user}, //SPA fieldsSearched, params.search, fieldsPerModel, diff --git a/src/routes/resources.js b/src/routes/resources.js index 5e3912c1a..7fbf4ef40 100644 --- a/src/routes/resources.js +++ b/src/routes/resources.js @@ -16,6 +16,7 @@ module.exports = function Resources(app, model) { this.list = (request, response, next) => { const params = request.query; + params.userRequest = request.user; //SPA const fieldsPerModel = new ParamsFieldsDeserializer(params.fields).perform(); return new Implementation.ResourcesGetter(model, lianaOptions, params) @@ -29,7 +30,7 @@ module.exports = function Resources(app, model) { model, records, integrator, - null, + {userRequest: params.userRequest}, //SPA fieldsSearched, params.search, fieldsPerModel, @@ -85,6 +86,7 @@ module.exports = function Resources(app, model) { model, record, integrator, + {userRequest: params.userRequest}, //SPA ).perform()) .then((record) => { response.send(record); @@ -103,6 +105,7 @@ module.exports = function Resources(app, model) { model, updatedRecord, integrator, + {userRequest: params.userRequest}, //SPA ).perform()) .then((updatedRecord) => { response.send(updatedRecord); diff --git a/src/serializers/resource.js b/src/serializers/resource.js index b0115bc5b..2aecb6845 100644 --- a/src/serializers/resource.js +++ b/src/serializers/resource.js @@ -158,6 +158,7 @@ function ResourceSerializer( formatFields(records); } + const userRequest = meta?meta.userRequest:null; //SPA return new P((resolve) => { if (_.isArray(records)) { let smartFieldsValuesInjector; @@ -167,6 +168,7 @@ function ResourceSerializer( record, modelName, fieldsPerModel, + userRequest, //SPA ); return smartFieldsValuesInjector.perform(); }) @@ -178,7 +180,7 @@ function ResourceSerializer( return result; })); } else { - resolve(new SmartFieldsValuesInjector(records, modelName, fieldsPerModel).perform()); + resolve(new SmartFieldsValuesInjector(records, modelName, fieldsPerModel, userRequest).perform()); //SPA } }) .then(() => { diff --git a/src/services/smart-fields-values-injector.js b/src/services/smart-fields-values-injector.js index c98ca0a99..89fcec2b7 100644 --- a/src/services/smart-fields-values-injector.js +++ b/src/services/smart-fields-values-injector.js @@ -23,14 +23,14 @@ function SmartFieldsValuesInjector( } // eslint-disable-next-line - function setSmartFieldValue(record, field, modelName) { + function setSmartFieldValue(record, field, modelName, userRequest) { //SPA if (field.value) { logger.warn(`DEPRECATION WARNING: Smart Fields "value" method is deprecated. Please use "get" method in your collection ${modelName} instead.`); } let value; try { - value = field.get ? field.get(record) : field.value(record); + value = field.get ? field.get(record, userRequest) : field.value(record); //SPA } catch (error) { logger.error(`Cannot retrieve the ${field.field} value because of an internal error in the getter implementation: `, error); } @@ -81,7 +81,7 @@ function SmartFieldsValuesInjector( return null; } - return setSmartFieldValue(record, field, modelName); + return setSmartFieldValue(record, field, modelName, userRequest); //SPA } if (!record[field.field] && _.isArray(field.type)) { @@ -105,6 +105,7 @@ function SmartFieldsValuesInjector( record[field.field], fieldAssociation, modelNameAssociation, + userRequest, //SPA ); } From 56949fb1332ad9ec25755d5be690e4a960a3f76a Mon Sep 17 00:00:00 2001 From: Sebastien P Date: Tue, 19 Jan 2021 18:07:06 +0100 Subject: [PATCH 2/2] fix --- src/routes/associations.js | 442 ++++++++++++++++++++++--------------- 1 file changed, 260 insertions(+), 182 deletions(-) diff --git a/src/routes/associations.js b/src/routes/associations.js index e5b915fa4..3e8da21ab 100644 --- a/src/routes/associations.js +++ b/src/routes/associations.js @@ -1,30 +1,60 @@ -const _ = require('lodash'); -const nodePath = require('path'); -const SchemaUtil = require('../utils/schema'); -const auth = require('../services/auth'); -const path = require('../services/path'); -const ResourceSerializer = require('../serializers/resource'); -const Schemas = require('../generators/schemas'); -const CSVExporter = require('../services/csv-exporter'); -const ResourceDeserializer = require('../deserializers/resource'); -const IdsFromRequestRetriever = require('../services/ids-from-request-retriever'); -const ParamsFieldsDeserializer = require('../deserializers/params-fields'); +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +var _ = require('lodash'); + +var nodePath = require('path'); + +var SchemaUtil = require('../utils/schema'); + +var auth = require('../services/auth'); + +var path = require('../services/path'); + +var ResourceSerializer = require('../serializers/resource'); + +var Schemas = require('../generators/schemas'); + +var CSVExporter = require('../services/csv-exporter'); + +var ResourceDeserializer = require('../deserializers/resource'); + +var IdsFromRequestRetriever = require('../services/ids-from-request-retriever'); + +var ParamsFieldsDeserializer = require('../deserializers/params-fields'); module.exports = function Associations(app, model, Implementation, integrator, opts) { - const modelName = Implementation.getModelName(model); - const schema = Schemas.schemas[modelName]; + var modelName = Implementation.getModelName(model); + var schema = Schemas.schemas[modelName]; function getAssociationField(associationName) { - const field = _.find(schema.fields, { field: associationName }); + var field = _.find(schema.fields, { + field: associationName + }); + if (field && field.reference) { return field.reference.split('.')[0]; } + return null; } function getAssociation(request) { - const pathSplit = request.route.path.split('/'); - let associationName = pathSplit[pathSplit.length - 1]; + var pathSplit = request.route.path.split('/'); + var associationName = pathSplit[pathSplit.length - 1]; if (nodePath.extname(associationName) === '.csv') { associationName = nodePath.basename(associationName, '.csv'); @@ -32,200 +62,248 @@ module.exports = function Associations(app, model, Implementation, integrator, o associationName = pathSplit[pathSplit.length - 2]; } - return { associationName }; + return { + associationName: associationName + }; } function getContext(request) { - const association = getAssociation(request); - const params = _.extend(request.query, request.params, association); - params.userRequest = request.user;//SPA - const models = Implementation.getModels(); - const associationField = getAssociationField(params.associationName); - const associationModel = _.find(models, (refModel) => - Implementation.getModelName(refModel) === associationField); - - return { params, associationModel }; + var association = getAssociation(request); + + var params = _.extend(request.query, request.params, association); + + var models = Implementation.getModels(); + var associationField = getAssociationField(params.associationName); + + var associationModel = _.find(models, function (refModel) { + return Implementation.getModelName(refModel) === associationField; + }); + + return { + params: params, + associationModel: associationModel + }; } function list(request, response, next) { - const { params, associationModel } = getContext(request); - const fieldsPerModel = new ParamsFieldsDeserializer(params.fields).perform(); - - return new Implementation.HasManyGetter(model, associationModel, opts, params) - .perform() - .then(([records, fieldsSearched]) => new ResourceSerializer( - Implementation, - associationModel, - records, - integrator, - {userRequest: request.user}, //SPA - fieldsSearched, - params.search, - fieldsPerModel, - ).perform()) - .then((records) => response.send(records)) - .catch(next); + var _getContext = getContext(request), + params = _getContext.params, + associationModel = _getContext.associationModel; + params.userRequest = request.user; + + var fieldsPerModel = new ParamsFieldsDeserializer(params.fields).perform(); + return new Implementation.HasManyGetter(model, associationModel, opts, params).perform().then(function (_ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + records = _ref2[0], + fieldsSearched = _ref2[1]; + + return new ResourceSerializer(Implementation, associationModel, records, integrator, {userRequest: params.userRequest}, fieldsSearched, params.search, fieldsPerModel).perform(); //SPA + }).then(function (records) { + return response.send(records); + })["catch"](next); } function count(request, response, next) { - const { params, associationModel } = getContext(request); + var _getContext2 = getContext(request), + params = _getContext2.params, + associationModel = _getContext2.associationModel; - return new Implementation.HasManyGetter(model, associationModel, opts, params) - .count() - .then((recordsCount) => response.send({ count: recordsCount })) - .catch(next); + return new Implementation.HasManyGetter(model, associationModel, opts, params).count().then(function (recordsCount) { + return response.send({ + count: recordsCount + }); + })["catch"](next); } function exportCSV(request, response, next) { - const { params, associationModel } = getContext(request); - - const recordsExporter = new Implementation.ResourcesExporter( - model, - opts, - params, - associationModel, - ); - return new CSVExporter( - params, response, - Implementation.getModelName(associationModel), recordsExporter, - ) - .perform() - .catch(next); + var _getContext3 = getContext(request), + params = _getContext3.params, + associationModel = _getContext3.associationModel; + + var recordsExporter = new Implementation.ResourcesExporter(model, opts, params, associationModel); + return new CSVExporter(params, response, Implementation.getModelName(associationModel), recordsExporter).perform()["catch"](next); } function add(request, response, next) { - const params = _.extend(request.params, getAssociation(request)); - const data = request.body; - const models = Implementation.getModels(); - const associationField = getAssociationField(params.associationName); - const associationModel = _.find( - models, - (innerModel) => Implementation.getModelName(innerModel) === associationField, - ); - - return new Implementation.HasManyAssociator( - model, associationModel, opts, - params, data, - ) - .perform() - .then(() => { response.status(204).send(); }) - .catch(next); + var params = _.extend(request.params, getAssociation(request)); + + var data = request.body; + var models = Implementation.getModels(); + var associationField = getAssociationField(params.associationName); + + var associationModel = _.find(models, function (innerModel) { + return Implementation.getModelName(innerModel) === associationField; + }); + + return new Implementation.HasManyAssociator(model, associationModel, opts, params, data).perform().then(function () { + response.status(204).send(); + })["catch"](next); } - async function remove(request, response, next) { - const { params, associationModel } = getContext(request); - - let body; - // NOTICE: There are three ways to receive request data from frontend: - // - Legacy: `{ body: { data: [ { id: 1, … }, { id: 2, … }, … ]} }`. - // - IDs (select some) - // - Or query params (select all). - // - // The HasManyDissociator currently accepts a `data` parameter that has to be formatted - // as the legacy one. - const hasBodyAttributes = request.body && request.body.data && request.body.data.attributes; - const isLegacyRequest = request.body && request.body.data && Array.isArray(request.body.data); - if (!hasBodyAttributes && isLegacyRequest) { - body = request.body; - } else if (hasBodyAttributes) { - const recordsGetter = async (attributes) => { - const [records] = await new Implementation.HasManyGetter( - model, - associationModel, - opts, - { - ...params, - ...attributes.allRecordsSubsetQuery, - page: attributes.page, - }, - ).perform(); - return records; - }; - const recordsCounter = async () => - new Implementation.HasManyGetter(model, associationModel, opts, params).count(); - const primaryKeysGetter = () => - Schemas.schemas[Implementation.getModelName(associationModel)]; - const ids = await new IdsFromRequestRetriever( - recordsGetter, - recordsCounter, - primaryKeysGetter, - ).perform(request); - body = { data: ids.map((id) => ({ id })) }; - } + function remove(_x, _x2, _x3) { + return _remove.apply(this, arguments); + } + + function _remove() { + _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(request, response, next) { + var _getContext4, params, associationModel, body, hasBodyAttributes, isLegacyRequest, recordsGetter, recordsCounter, primaryKeysGetter, ids; + + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _getContext4 = getContext(request), params = _getContext4.params, associationModel = _getContext4.associationModel; + // NOTICE: There are three ways to receive request data from frontend: + // - Legacy: `{ body: { data: [ { id: 1, … }, { id: 2, … }, … ]} }`. + // - IDs (select some) + // - Or query params (select all). + // + // The HasManyDissociator currently accepts a `data` parameter that has to be formatted + // as the legacy one. + hasBodyAttributes = request.body && request.body.data && request.body.data.attributes; + isLegacyRequest = request.body && request.body.data && Array.isArray(request.body.data); + + if (!(!hasBodyAttributes && isLegacyRequest)) { + _context3.next = 7; + break; + } + + body = request.body; + _context3.next = 15; + break; + + case 7: + if (!hasBodyAttributes) { + _context3.next = 15; + break; + } + + recordsGetter = /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(attributes) { + var _yield$Implementation, _yield$Implementation2, records; + + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return new Implementation.HasManyGetter(model, associationModel, opts, _objectSpread(_objectSpread(_objectSpread({}, params), attributes.allRecordsSubsetQuery), {}, { + page: attributes.page + })).perform(); + + case 2: + _yield$Implementation = _context.sent; + _yield$Implementation2 = (0, _slicedToArray2["default"])(_yield$Implementation, 1); + records = _yield$Implementation2[0]; + return _context.abrupt("return", records); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function recordsGetter(_x4) { + return _ref3.apply(this, arguments); + }; + }(); - return new Implementation.HasManyDissociator( - model, - associationModel, - opts, - params, - body, - ) - .perform() - .then(() => { response.status(204).send(); }) - .catch(next); + recordsCounter = /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", new Implementation.HasManyGetter(model, associationModel, opts, params).count()); + + case 1: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + + return function recordsCounter() { + return _ref4.apply(this, arguments); + }; + }(); + + primaryKeysGetter = function primaryKeysGetter() { + return Schemas.schemas[Implementation.getModelName(associationModel)]; + }; + + _context3.next = 13; + return new IdsFromRequestRetriever(recordsGetter, recordsCounter, primaryKeysGetter).perform(request); + + case 13: + ids = _context3.sent; + body = { + data: ids.map(function (id) { + return { + id: id + }; + }) + }; + + case 15: + return _context3.abrupt("return", new Implementation.HasManyDissociator(model, associationModel, opts, params, body).perform().then(function () { + response.status(204).send(); + })["catch"](next)); + + case 16: + case "end": + return _context3.stop(); + } + } + }, _callee3); + })); + return _remove.apply(this, arguments); } function update(request, response, next) { - const params = _.extend(request.params, getAssociation(request)); - const data = request.body; - const models = Implementation.getModels(); - const associationField = getAssociationField(params.associationName); - const associationModel = _.find( - models, - (innerModel) => Implementation.getModelName(innerModel) === associationField, - ); - - return new Implementation.BelongsToUpdater( - model, - associationModel, - opts, - params, - data, - ) - .perform() - .then(() => { response.status(204).send(); }) - .catch(next); + var params = _.extend(request.params, getAssociation(request)); + + var data = request.body; + var models = Implementation.getModels(); + var associationField = getAssociationField(params.associationName); + + var associationModel = _.find(models, function (innerModel) { + return Implementation.getModelName(innerModel) === associationField; + }); + + return new Implementation.BelongsToUpdater(model, associationModel, opts, params, data).perform().then(function () { + response.status(204).send(); + })["catch"](next); } function updateEmbeddedDocument(association) { - return (request, response, next) => - new ResourceDeserializer(Implementation, model, request.body, false) - .perform() - .then((record) => new Implementation - .EmbeddedDocumentUpdater(model, request.params, association, record) - .perform()) - .then(() => response.status(204).send()) - .catch(next); + return function (request, response, next) { + return new ResourceDeserializer(Implementation, model, request.body, false).perform().then(function (record) { + return new Implementation.EmbeddedDocumentUpdater(model, request.params, association, record).perform(); + }).then(function () { + return response.status(204).send(); + })["catch"](next); + }; } - this.perform = () => { + this.perform = function () { // NOTICE: HasMany associations routes - _.each(SchemaUtil.getHasManyAssociations(schema), (association) => { - app.get(path.generate(`${modelName}/:recordId/relationships/${ - association.field}.csv`, opts), auth.ensureAuthenticated, exportCSV); - app.get(path.generate(`${modelName}/:recordId/relationships/${ - association.field}`, opts), auth.ensureAuthenticated, list); - app.get( - path.generate(`${modelName}/:recordId/relationships/${association.field}/count`, opts), - auth.ensureAuthenticated, - count, - ); - app.post(path.generate(`${modelName}/:recordId/relationships/${ - association.field}`, opts), auth.ensureAuthenticated, add); - // NOTICE: This route only works for embedded has many - app.put( - path.generate(`${modelName}/:recordId/relationships/${association.field}/:recordIndex`, opts), - auth.ensureAuthenticated, - updateEmbeddedDocument(association.field), - ); - app.delete(path.generate(`${modelName}/:recordId/relationships/${ - association.field}`, opts), auth.ensureAuthenticated, remove); - }); + _.each(SchemaUtil.getHasManyAssociations(schema), function (association) { + app.get(path.generate("".concat(modelName, "/:recordId/relationships/").concat(association.field, ".csv"), opts), auth.ensureAuthenticated, exportCSV); + app.get(path.generate("".concat(modelName, "/:recordId/relationships/").concat(association.field), opts), auth.ensureAuthenticated, list); + app.get(path.generate("".concat(modelName, "/:recordId/relationships/").concat(association.field, "/count"), opts), auth.ensureAuthenticated, count); + app.post(path.generate("".concat(modelName, "/:recordId/relationships/").concat(association.field), opts), auth.ensureAuthenticated, add); // NOTICE: This route only works for embedded has many + + app.put(path.generate("".concat(modelName, "/:recordId/relationships/").concat(association.field, "/:recordIndex"), opts), auth.ensureAuthenticated, updateEmbeddedDocument(association.field)); + app["delete"](path.generate("".concat(modelName, "/:recordId/relationships/").concat(association.field), opts), auth.ensureAuthenticated, remove); + }); // NOTICE: belongsTo associations routes + - // NOTICE: belongsTo associations routes - _.each(SchemaUtil.getBelongsToAssociations(schema), (association) => { - app.put(path.generate(`${modelName}/:recordId/relationships/${ - association.field}`, opts), auth.ensureAuthenticated, update); + _.each(SchemaUtil.getBelongsToAssociations(schema), function (association) { + app.put(path.generate("".concat(modelName, "/:recordId/relationships/").concat(association.field), opts), auth.ensureAuthenticated, update); }); }; -}; +}; \ No newline at end of file