Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix deepFiltering with draft & publish #8356

Merged
merged 3 commits into from
Oct 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 25 additions & 6 deletions packages/strapi-connector-bookshelf/lib/buildQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const BOOLEAN_OPERATORS = ['or'];
const buildQuery = ({ model, filters }) => qb => {
if (_.has(filters, 'where') && Array.isArray(filters.where) && filters.where.length > 0) {
qb.distinct();
buildJoinsAndFilter(qb, model, filters.where);
buildJoinsAndFilter(qb, model, filters);
}

if (_.has(filters, 'sort')) {
Expand Down Expand Up @@ -45,9 +45,11 @@ const buildQuery = ({ model, filters }) => qb => {
* Add joins and where filters
* @param {Object} qb - knex query builder
* @param {Object} model - Bookshelf model
* @param {Array<Object>} whereClauses - an array of where clause
* @param {Object} filters - The query filters
*/
const buildJoinsAndFilter = (qb, model, whereClauses) => {
const buildJoinsAndFilter = (qb, model, filters) => {
const { where: whereClauses } = filters;

/**
* Returns an alias for a name (simple incremental alias name)
* @param {string} name - name to alias
Expand Down Expand Up @@ -210,12 +212,29 @@ const buildJoinsAndFilter = (qb, model, whereClauses) => {
});
};

const aliasedWhereClauses = buildWhereClauses(whereClauses, { model });
/**
* Add queries on tree's joins (deep search) based on given filters
* @param tree - joins tree
*/
const addFiltersQueriesToJoinTree = tree => {
_.each(tree.joins, value => {
const { alias, model } = value;

runPopulateQueries(
toQueries({
publicationState: { query: filters.publicationState, model, alias },
}),
qb
);
addFiltersQueriesToJoinTree(value);
});
};

buildJoinsFromTree(qb, tree);
const aliasedWhereClauses = buildWhereClauses(whereClauses, { model });
aliasedWhereClauses.forEach(w => buildWhereClause({ qb, ...w }));

return;
buildJoinsFromTree(qb, tree);
addFiltersQueriesToJoinTree(tree);
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ const {
const optionsMap = {
publicationState: {
queries: {
[DP_PUB_STATE_LIVE]: ({ model }) => qb => {
[DP_PUB_STATE_LIVE]: ({ model, alias }) => qb => {
const { collectionName } = model;
qb.whereNotNull(`${collectionName}.${PUBLISHED_AT_ATTRIBUTE}`);
qb.whereNotNull(`${alias || collectionName}.${PUBLISHED_AT_ATTRIBUTE}`);
},
[DP_PUB_STATE_PREVIEW]: () => null,
},
Expand Down
102 changes: 64 additions & 38 deletions packages/strapi-connector-mongoose/lib/buildQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ const utils = require('./utils')();
const populateQueries = require('./utils/populate-queries');
const {
hasDeepFilters,
contentTypes: { hasDraftAndPublish },
contentTypes: {
constants: { DP_PUB_STATES },
hasDraftAndPublish,
},
} = require('strapi-utils');

const combineSearchAndWhere = (search = [], wheres = []) => {
Expand Down Expand Up @@ -134,12 +137,11 @@ const buildDeepQuery = ({ model, filters, search, populate }) => {
populate,
where: filters.where,
});
const customQueryOptions = _.pick(filters, ['publicationState']);

// Init the query
let query = model
.aggregate(
buildQueryAggregate(model, {
buildQueryAggregate(model, filters, {
paths: _.merge({}, populatePaths, wherePaths),
})
)
Expand All @@ -165,8 +167,7 @@ const buildDeepQuery = ({ model, filters, search, populate }) => {
$in: ids,
},
},
null,
{ custom: customQueryOptions }
null
)
.populate(populate);

Expand Down Expand Up @@ -292,7 +293,7 @@ const recursiveCastedWherePaths = (whereClauses, { model }) => {
* Builds an object based on paths:
* [
* 'articles',
* 'articles.tags.cateogry',
* 'articles.tags.category',
* 'articles.tags.label',
* ] => {
* articles: {
Expand All @@ -307,14 +308,15 @@ const recursiveCastedWherePaths = (whereClauses, { model }) => {
const pathsToTree = paths => paths.reduce((acc, path) => _.merge(acc, _.set({}, path, {})), {});

/**
* Builds the aggregations pipeling of the query
* Builds the aggregations pipeline of the query
* @param {Object} model - Queried model
* @param {Object} filters - The query filters
* @param {Object} options - Options
* @param {Object} options.paths - A tree of paths to aggregate e.g { article : { tags : { label: {}}}}
*/
const buildQueryAggregate = (model, { paths } = {}) => {
const buildQueryAggregate = (model, filters, { paths } = {}) => {
return Object.keys(paths).reduce((acc, key) => {
return acc.concat(buildLookup({ model, key, paths: paths[key] }));
return acc.concat(buildLookup({ model, key, paths: paths[key], filters }));
}, []);
};

Expand All @@ -325,7 +327,7 @@ const buildQueryAggregate = (model, { paths } = {}) => {
* @param {string} options.key - The attribute name to lookup on the model
* @param {Object} options.paths - A tree of paths to aggregate inside the current lookup e.g { { tags : { label: {}}}
*/
const buildLookup = ({ model, key, paths }) => {
const buildLookup = ({ model, key, paths, filters }) => {
const assoc = model.associations.find(a => a.alias === key);
const assocModel = strapi.db.getModelByAssoc(assoc);

Expand All @@ -341,8 +343,8 @@ const buildLookup = ({ model, key, paths }) => {
localAlias: `$${assoc.alias}`,
},
pipeline: []
.concat(buildLookupMatch({ assoc }))
.concat(buildQueryAggregate(assocModel, { paths })),
.concat(buildLookupMatch({ assoc, assocModel, filters }))
.concat(buildQueryAggregate(assocModel, filters, { paths })),
},
},
];
Expand All @@ -351,65 +353,87 @@ const buildLookup = ({ model, key, paths }) => {
/**
* Build a lookup match expression (equivalent to a SQL join condition)
* @param {Object} options - Options
* @param {Object} options.assoc - The association on which is based the ematching xpression
* @param {Object} options.assoc - The association on which is based the matching expression
*/
const buildLookupMatch = ({ assoc }) => {
const buildLookupMatch = ({ assoc, assocModel, filters = {} }) => {
const defaultMatches = [];

if (hasDraftAndPublish(assocModel) && DP_PUB_STATES.includes(filters.publicationState)) {
const dpQuery = populateQueries.publicationState[filters.publicationState];

if (_.isObject(dpQuery)) {
defaultMatches.push(dpQuery);
}
}

switch (assoc.nature) {
case 'oneToOne': {
return [
{
$match: {
$expr: {
$eq: [`$${assoc.via}`, '$$localId'],
},
$and: defaultMatches.concat({
$expr: {
$eq: [`$${assoc.via}`, '$$localId'],
},
}),
},
},
];
}
case 'oneToMany': {
return {
$match: {
$expr: {
$eq: [`$${assoc.via}`, '$$localId'],
},
$and: defaultMatches.concat({
$expr: {
$eq: [`$${assoc.via}`, '$$localId'],
},
}),
},
};
}
case 'oneWay':
case 'manyToOne': {
return {
$match: {
$expr: {
$eq: ['$$localAlias', '$_id'],
},
$and: defaultMatches.concat({
$expr: {
$eq: ['$$localAlias', '$_id'],
},
}),
},
};
}
case 'manyWay': {
return {
$match: {
$expr: {
$in: ['$_id', '$$localAlias'],
},
$and: defaultMatches.concat({
$expr: {
$in: ['$_id', '$$localAlias'],
},
}),
},
};
}
case 'manyToMany': {
if (assoc.dominant === true) {
return {
$match: {
$expr: {
$in: ['$_id', '$$localAlias'],
},
$and: defaultMatches.concat({
$expr: {
$in: ['$_id', '$$localAlias'],
},
}),
},
};
}

return {
$match: {
$expr: {
$in: ['$$localId', `$${assoc.via}`],
},
$and: defaultMatches.concat({
Convly marked this conversation as resolved.
Show resolved Hide resolved
$expr: {
$in: ['$$localId', `$${assoc.via}`],
},
}),
},
};
}
Expand All @@ -421,12 +445,14 @@ const buildLookupMatch = ({ assoc }) => {
},
{
$match: {
$expr: {
$and: [
{ $eq: [`$${assoc.via}.ref`, '$$localId'] },
{ $eq: [`$${assoc.via}.${assoc.filter}`, assoc.alias] },
],
},
$and: defaultMatches.concat({
$expr: {
$and: [
{ $eq: [`$${assoc.via}.ref`, '$$localId'] },
{ $eq: [`$${assoc.via}.${assoc.filter}`, assoc.alias] },
],
},
}),
},
},
];
Expand Down