diff --git a/CHANGELOG.md b/CHANGELOG.md index c17ae9eb..12bdcf12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### Added - Technical - Add babel. +### Changed +- Smart Segments - Prevent includes from queryBuilder to overwrite include from segment scope. + ## RELEASE 2.16.9 - 2018-11-08 ### Changed - Smart Fields - Display a warning to show Smart Fields declared without a field attribute. diff --git a/src/services/query-builder.js b/src/services/query-builder.js index cb5ac367..11588c30 100644 --- a/src/services/query-builder.js +++ b/src/services/query-builder.js @@ -24,20 +24,24 @@ function QueryBuilder(model, opts, params) { }; this.getIncludes = function (modelForIncludes, fieldNamesRequested) { - var includes = []; - _.values(modelForIncludes.associations).forEach(function (association) { - if (!fieldNamesRequested || - (fieldNamesRequested.indexOf(association.as) !== -1)) { - if (['HasOne', 'BelongsTo'].indexOf(association.associationType) > -1) { - includes.push({ - model: association.target.unscoped(), - as: association.associationAccessor - }); - } - } - }); - - return includes; + return _.values(modelForIncludes.associations) + .filter(function (association) { + return ( + (!fieldNamesRequested || + fieldNamesRequested.includes(association.as)) && + ['HasOne', 'BelongsTo'].includes(association.associationType) && + // Don't include models that are already included by the segment scope + (modelForIncludes._scope.include || []).every(function (include) { + return include.model !== association.target + }) + ); + }) + .map(function (association) { + return { + model: association.target.unscoped(), + as: association.associationAccessor + }; + }); }; this.getOrder = function (aliasName) { diff --git a/src/services/resources-getter.js b/src/services/resources-getter.js index c9c9a99f..eeab6976 100644 --- a/src/services/resources-getter.js +++ b/src/services/resources-getter.js @@ -116,7 +116,7 @@ function ResourcesGetter(model, opts, params) { function getRecords() { var scope = segmentScope ? model.scope(segmentScope) : model.unscoped(); - var include = queryBuilder.getIncludes(model, fieldNamesRequested); + var include = queryBuilder.getIncludes(scope, fieldNamesRequested); return getWhere() .then(function (where) { @@ -157,7 +157,7 @@ function ResourcesGetter(model, opts, params) { function countRecords() { var scope = segmentScope ? model.scope(segmentScope) : model.unscoped(); - var include = queryBuilder.getIncludes(model, fieldNamesRequested); + var include = queryBuilder.getIncludes(scope, fieldNamesRequested); return getWhere() .then(function (where) {