610 lines
16 KiB
JavaScript
Raw Normal View History

2019-07-15 15:33:42 +02:00
'use strict';
/**
* Implementation of model queries for bookshelf
*/
const _ = require('lodash');
const {
convertRestQueryParams,
buildQuery,
models: modelUtils,
} = require('strapi-utils');
module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
/* Utils */
// association key
const assocKeys = model.associations.map(ast => ast.alias);
2019-10-22 18:01:03 +02:00
// component keys
const componentKeys = Object.keys(model.attributes).filter(key => {
return model.attributes[key].type === 'component';
2019-07-15 15:33:42 +02:00
});
const timestamps = _.get(model, ['options', 'timestamps'], []);
2019-07-15 15:33:42 +02:00
// Returns an object with relation keys only to create relations in DB
const pickRelations = values => {
return _.pick(values, assocKeys);
};
// keys to exclude to get attribute keys
2019-10-22 18:01:03 +02:00
const excludedKeys = assocKeys.concat(componentKeys);
2019-07-15 15:33:42 +02:00
// Returns an object without relational keys to persist in DB
const selectAttributes = values => {
return _.pickBy(values, (value, key) => {
if (Array.isArray(timestamps) && timestamps.includes(key)) {
return false;
}
return !excludedKeys.includes(key) && _.has(model.allAttributes, key);
});
2019-07-15 15:33:42 +02:00
};
2019-07-24 17:16:50 +02:00
const wrapTransaction = (fn, { transacting } = {}) => {
const db = strapi.connections[model.connection];
if (transacting) return fn(transacting);
return db.transaction(trx => fn(trx));
};
2019-07-15 15:33:42 +02:00
/**
2019-07-18 14:39:41 +02:00
* Find one entry based on params
2019-07-15 15:33:42 +02:00
*/
async function findOne(params, populate, { transacting } = {}) {
2019-07-15 15:33:42 +02:00
const primaryKey = params[model.primaryKey] || params.id;
if (primaryKey) {
params = {
[model.primaryKey]: primaryKey,
};
}
2019-07-17 00:03:38 +02:00
const entry = await model.forge(params).fetch({
2019-07-30 11:22:44 +02:00
withRelated: populate,
transacting,
2019-07-15 15:33:42 +02:00
});
2019-07-17 00:03:38 +02:00
return entry ? entry.toJSON() : null;
2019-07-15 15:33:42 +02:00
}
/**
* Find multiple entries based on params
*/
2019-07-24 17:16:50 +02:00
function find(params, populate, { transacting } = {}) {
2019-07-15 15:33:42 +02:00
const filters = convertRestQueryParams(params);
return model
.query(buildQuery({ model, filters }))
2019-07-29 18:00:01 +02:00
.fetchAll({
2019-07-30 11:22:44 +02:00
withRelated: populate,
2019-07-29 18:00:01 +02:00
transacting,
})
2019-07-15 15:33:42 +02:00
.then(results => results.toJSON());
}
/**
* Count entries based on filters
*/
function count(params = {}) {
const { where } = convertRestQueryParams(params);
return model.query(buildQuery({ model, filters: { where } })).count();
}
2019-07-24 17:16:50 +02:00
async function create(values, { transacting } = {}) {
2019-07-15 15:33:42 +02:00
const relations = pickRelations(values);
const data = selectAttributes(values);
2019-07-15 15:33:42 +02:00
const runCreate = async trx => {
// Create entry with no-relational data.
const entry = await model.forge(data).save(null, { transacting: trx });
2019-10-22 18:01:03 +02:00
await createComponents(entry, values, { transacting: trx });
2019-07-15 15:33:42 +02:00
return model.updateRelations(
{ id: entry.id, values: relations },
{ transacting: trx }
);
};
2019-07-15 15:33:42 +02:00
return wrapTransaction(runCreate, { transacting });
2019-07-15 15:33:42 +02:00
}
2019-07-24 17:16:50 +02:00
async function update(params, values, { transacting } = {}) {
const entry = await model.forge(params).fetch({ transacting });
2019-07-15 15:33:42 +02:00
if (!entry) {
const err = new Error('entry.notFound');
err.status = 404;
throw err;
}
// Extract values related to relational data.
const relations = pickRelations(values);
const data = selectAttributes(values);
2019-07-15 15:33:42 +02:00
const runUpdate = async trx => {
2019-07-16 20:52:31 +02:00
const updatedEntry =
Object.keys(data).length > 0
2019-07-17 14:28:36 +02:00
? await entry.save(data, {
transacting: trx,
method: 'update',
patch: true,
})
2019-07-16 20:52:31 +02:00
: entry;
2019-10-22 18:01:03 +02:00
await updateComponents(updatedEntry, values, { transacting: trx });
2019-07-15 15:33:42 +02:00
if (Object.keys(relations).length > 0) {
return model.updateRelations(
Object.assign(params, { values: relations }),
{ transacting: trx }
);
}
2019-07-15 15:33:42 +02:00
return this.findOne(params, null, { transacting: trx });
};
2019-07-16 20:52:31 +02:00
return wrapTransaction(runUpdate, { transacting });
2019-07-15 15:33:42 +02:00
}
2019-07-24 17:16:50 +02:00
async function deleteOne(params, { transacting } = {}) {
const entry = await model.forge(params).fetch({ transacting });
2019-07-15 15:33:42 +02:00
if (!entry) {
const err = new Error('entry.notFound');
err.status = 404;
throw err;
}
const values = {};
model.associations.map(association => {
switch (association.nature) {
case 'oneWay':
case 'oneToOne':
case 'manyToOne':
case 'oneToManyMorph':
values[association.alias] = null;
break;
2019-07-24 17:16:50 +02:00
case 'manyWay':
2019-07-15 15:33:42 +02:00
case 'oneToMany':
case 'manyToMany':
case 'manyToManyMorph':
values[association.alias] = [];
break;
default:
}
});
2019-07-24 17:16:50 +02:00
await model.updateRelations({ ...params, values }, { transacting });
2019-07-15 15:33:42 +02:00
const runDelete = async trx => {
2019-10-22 18:01:03 +02:00
await deleteComponents(entry, { transacting: trx });
2019-07-24 17:16:50 +02:00
await model.forge(params).destroy({ transacting: trx, require: false });
return entry.toJSON();
2019-07-15 15:33:42 +02:00
};
2019-07-24 17:16:50 +02:00
return wrapTransaction(runDelete, { transacting });
2019-07-15 15:33:42 +02:00
}
2019-07-24 17:16:50 +02:00
async function deleteMany(params, { transacting } = {}) {
2019-07-16 20:11:34 +02:00
const primaryKey = params[model.primaryKey] || params.id;
2019-07-24 17:16:50 +02:00
if (primaryKey) return deleteOne(params, { transacting });
2019-07-16 20:11:34 +02:00
2019-07-24 17:16:50 +02:00
const entries = await find(params, null, { transacting });
return await Promise.all(
entries.map(entry => deleteOne({ id: entry.id }, { transacting }))
);
2019-07-16 20:11:34 +02:00
}
2019-07-15 15:33:42 +02:00
function search(params, populate) {
// Convert `params` object to filters compatible with Bookshelf.
const filters = modelUtils.convertParams(modelKey, params);
return model
.query(qb => {
buildSearchQuery(qb, model, params);
if (filters.sort) {
qb.orderBy(filters.sort.key, filters.sort.order);
}
if (filters.start) {
qb.offset(_.toNumber(filters.start));
}
if (filters.limit) {
qb.limit(_.toNumber(filters.limit));
}
})
.fetchAll({
2019-07-30 11:22:44 +02:00
withRelated: populate,
})
.then(results => results.toJSON());
2019-07-15 15:33:42 +02:00
}
function countSearch(params) {
2019-07-26 10:57:27 +02:00
return model
.query(qb => {
buildSearchQuery(qb, model, params);
})
.count();
2019-07-15 15:33:42 +02:00
}
2019-10-22 18:01:03 +02:00
async function createComponents(entry, values, { transacting }) {
if (componentKeys.length === 0) return;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const joinModel = model.componentsJoinModel;
2019-07-15 15:33:42 +02:00
const { foreignKey } = joinModel;
2019-10-22 18:01:03 +02:00
for (let key of componentKeys) {
2019-07-15 15:33:42 +02:00
const attr = model.attributes[key];
2019-10-22 18:01:03 +02:00
const { component, required = false, repeatable = false } = attr;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const componentModel = strapi.components[component];
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const createComponentAndLink = async ({ value, order }) => {
2019-07-24 17:16:50 +02:00
return strapi
2019-10-22 18:01:03 +02:00
.query(componentModel.uid)
2019-07-24 17:16:50 +02:00
.create(value, { transacting })
2019-10-22 18:01:03 +02:00
.then(component => {
2019-07-15 15:33:42 +02:00
return joinModel.forge().save(
{
[foreignKey]: entry.id,
2019-10-22 18:01:03 +02:00
component_type: componentModel.collectionName,
component_id: component.id,
2019-07-15 15:33:42 +02:00
field: key,
order,
},
{ transacting }
);
});
};
if (required === true && !_.has(values, key)) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} is required`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
if (!_.has(values, key)) continue;
2019-10-22 18:01:03 +02:00
const componentValue = values[key];
2019-07-15 15:33:42 +02:00
if (repeatable === true) {
2019-10-22 18:01:03 +02:00
validateRepeatableInput(componentValue, { key, ...attr });
2019-07-15 15:33:42 +02:00
await Promise.all(
2019-10-22 18:01:03 +02:00
componentValue.map((value, idx) =>
createComponentAndLink({ value, order: idx + 1 })
2019-07-15 15:33:42 +02:00
)
);
} else {
2019-10-22 18:01:03 +02:00
validateNonRepeatableInput(componentValue, { key, ...attr });
2019-10-22 18:01:03 +02:00
if (componentValue === null) continue;
await createComponentAndLink({ value: componentValue, order: 1 });
2019-07-15 15:33:42 +02:00
}
}
}
2019-10-22 18:01:03 +02:00
async function updateComponents(entry, values, { transacting }) {
if (componentKeys.length === 0) return;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const joinModel = model.componentsJoinModel;
2019-07-15 15:33:42 +02:00
const { foreignKey } = joinModel;
2019-10-22 18:01:03 +02:00
for (let key of componentKeys) {
// if key isn't present then don't change the current component data
2019-07-15 15:33:42 +02:00
if (!_.has(values, key)) continue;
const attr = model.attributes[key];
2019-10-22 18:01:03 +02:00
const { component, repeatable = false } = attr;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const componentModel = strapi.components[component];
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const componentValue = values[key];
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const updateOrCreateComponentAndLink = async ({ value, order }) => {
2019-07-15 15:33:42 +02:00
// check if value has an id then update else create
2019-10-22 18:01:03 +02:00
if (_.has(value, componentModel.primaryKey)) {
2019-07-24 17:16:50 +02:00
return strapi
2019-10-22 18:01:03 +02:00
.query(componentModel.uid)
2019-07-24 17:16:50 +02:00
.update(
{
2019-10-22 18:01:03 +02:00
[componentModel.primaryKey]: value[componentModel.primaryKey],
2019-07-24 17:16:50 +02:00
},
value,
{ transacting }
)
2019-10-22 18:01:03 +02:00
.then(component => {
2019-07-15 15:33:42 +02:00
return joinModel
.forge()
.query({
where: {
[foreignKey]: entry.id,
2019-10-22 18:01:03 +02:00
component_type: componentModel.collectionName,
component_id: component.id,
2019-07-15 15:33:42 +02:00
field: key,
},
})
.save(
{
order,
},
{ transacting, patch: true, require: false }
);
});
}
// create
2019-07-24 17:16:50 +02:00
return strapi
2019-10-22 18:01:03 +02:00
.query(componentModel.uid)
2019-07-24 17:16:50 +02:00
.create(value, { transacting })
2019-10-22 18:01:03 +02:00
.then(component => {
2019-07-15 15:33:42 +02:00
return joinModel.forge().save(
{
[foreignKey]: entry.id,
2019-10-22 18:01:03 +02:00
component_type: componentModel.collectionName,
component_id: component.id,
2019-07-15 15:33:42 +02:00
field: key,
order,
},
{ transacting }
);
});
};
if (repeatable === true) {
2019-10-22 18:01:03 +02:00
validateRepeatableInput(componentValue, { key, ...attr });
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
await deleteOldComponents(entry, componentValue, {
2019-07-15 15:33:42 +02:00
key,
joinModel,
2019-10-22 18:01:03 +02:00
componentModel,
2019-07-15 15:33:42 +02:00
transacting,
});
await Promise.all(
2019-10-22 18:01:03 +02:00
componentValue.map((value, idx) => {
return updateOrCreateComponentAndLink({ value, order: idx + 1 });
2019-07-15 15:33:42 +02:00
})
);
} else {
2019-10-22 18:01:03 +02:00
validateNonRepeatableInput(componentValue, { key, ...attr });
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
await deleteOldComponents(entry, componentValue, {
2019-07-15 15:33:42 +02:00
key,
joinModel,
2019-10-22 18:01:03 +02:00
componentModel,
2019-07-15 15:33:42 +02:00
transacting,
});
2019-10-22 18:01:03 +02:00
if (componentValue === null) continue;
2019-10-22 18:01:03 +02:00
await updateOrCreateComponentAndLink({
value: componentValue,
order: 1,
});
2019-07-15 15:33:42 +02:00
}
}
return;
}
2019-10-22 18:01:03 +02:00
async function deleteOldComponents(
2019-07-15 15:33:42 +02:00
entry,
2019-10-22 18:01:03 +02:00
componentValue,
{ key, joinModel, componentModel, transacting }
2019-07-15 15:33:42 +02:00
) {
2019-10-22 18:01:03 +02:00
const componentArr = Array.isArray(componentValue)
? componentValue
: [componentValue];
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const idsToKeep = componentArr
.filter(el => _.has(el, componentModel.primaryKey))
.map(el => el[componentModel.primaryKey].toString());
2019-07-15 15:33:42 +02:00
const allIds = await joinModel
.forge()
.query(qb => {
qb.where(joinModel.foreignKey, entry.id).andWhere('field', key);
})
.fetchAll({ transacting })
2019-10-22 18:01:03 +02:00
.map(el => el.get('component_id').toString());
2019-07-15 15:33:42 +02:00
// verify the provided ids are realted to this entity.
idsToKeep.forEach(id => {
2019-07-24 17:16:50 +02:00
if (!allIds.includes(id)) {
2019-07-15 15:33:42 +02:00
const err = new Error(
2019-10-22 18:01:03 +02:00
`Some of the provided components in ${key} are not related to the entity`
2019-07-15 15:33:42 +02:00
);
err.status = 400;
throw err;
}
});
const idsToDelete = _.difference(allIds, idsToKeep);
if (idsToDelete.length > 0) {
await joinModel
.forge()
2019-10-22 18:01:03 +02:00
.query(qb =>
qb.whereIn('component_id', idsToDelete).andWhere('field', key)
)
2019-07-15 15:33:42 +02:00
.destroy({ transacting, require: false });
2019-07-24 17:16:50 +02:00
await strapi
2019-10-22 18:01:03 +02:00
.query(componentModel.uid)
2019-07-24 17:16:50 +02:00
.delete(
2019-10-22 18:01:03 +02:00
{ [`${componentModel.primaryKey}_in`]: idsToDelete },
2019-07-24 17:16:50 +02:00
{ transacting }
);
2019-07-15 15:33:42 +02:00
}
}
2019-10-22 18:01:03 +02:00
async function deleteComponents(entry, { transacting }) {
if (componentKeys.length === 0) return;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const joinModel = model.componentsJoinModel;
2019-07-15 15:33:42 +02:00
const { foreignKey } = joinModel;
2019-10-22 18:01:03 +02:00
for (let key of componentKeys) {
2019-07-15 15:33:42 +02:00
const attr = model.attributes[key];
2019-10-22 18:01:03 +02:00
const { component } = attr;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const componentModel = strapi.components[component];
2019-07-15 15:33:42 +02:00
const ids = await joinModel
.forge()
.query({
where: {
[foreignKey]: entry.id,
2019-10-22 18:01:03 +02:00
component_type: componentModel.collectionName,
2019-07-15 15:33:42 +02:00
field: key,
},
})
.fetchAll({ transacting })
2019-10-22 18:01:03 +02:00
.map(el => el.get('component_id'));
2019-07-15 15:33:42 +02:00
2019-07-24 17:16:50 +02:00
await strapi
2019-10-22 18:01:03 +02:00
.query(componentModel.uid)
.delete({ [`${componentModel.primaryKey}_in`]: ids }, { transacting });
2019-07-24 17:16:50 +02:00
2019-07-15 15:33:42 +02:00
await joinModel
.forge()
.query({
where: {
[foreignKey]: entry.id,
2019-10-22 18:01:03 +02:00
component_type: componentModel.collectionName,
2019-07-15 15:33:42 +02:00
field: key,
},
})
.destroy({ transacting, require: false });
}
}
return {
findOne,
find,
create,
update,
2019-07-16 20:11:34 +02:00
delete: deleteMany,
2019-07-15 15:33:42 +02:00
count,
search,
countSearch,
};
};
/**
* util to build search query
* @param {*} qb
* @param {*} model
* @param {*} params
*/
const buildSearchQuery = (qb, model, params) => {
const query = params._q;
2019-07-15 15:33:42 +02:00
const associations = model.associations.map(x => x.alias);
const searchText = Object.keys(model._attributes)
.filter(
attribute =>
attribute !== model.primaryKey && !associations.includes(attribute)
)
.filter(attribute =>
['string', 'text'].includes(model._attributes[attribute].type)
);
const searchInt = Object.keys(model._attributes)
.filter(
attribute =>
attribute !== model.primaryKey && !associations.includes(attribute)
)
.filter(attribute =>
['integer', 'decimal', 'float'].includes(
model._attributes[attribute].type
)
);
const searchBool = Object.keys(model._attributes)
.filter(
attribute =>
attribute !== model.primaryKey && !associations.includes(attribute)
)
.filter(attribute =>
['boolean'].includes(model._attributes[attribute].type)
);
if (!_.isNaN(_.toNumber(query))) {
searchInt.forEach(attribute => {
2019-07-26 10:57:27 +02:00
qb.orWhere(attribute, _.toNumber(query));
2019-07-15 15:33:42 +02:00
});
}
if (query === 'true' || query === 'false') {
searchBool.forEach(attribute => {
2019-07-26 10:57:27 +02:00
qb.orWhere(attribute, _.toNumber(query === 'true'));
2019-07-15 15:33:42 +02:00
});
}
// Search in columns with text using index.
switch (model.client) {
case 'mysql':
qb.orWhereRaw(
`MATCH(${searchText.join(',')}) AGAINST(? IN BOOLEAN MODE)`,
`*${query}*`
);
break;
case 'pg': {
const searchQuery = searchText.map(attribute =>
_.toLower(attribute) === attribute
? `to_tsvector(${attribute})`
2019-09-30 17:33:07 +02:00
: `to_tsvector("${attribute}")`
2019-07-15 15:33:42 +02:00
);
qb.orWhereRaw(`${searchQuery.join(' || ')} @@ plainto_tsquery(?)`, query);
2019-07-15 15:33:42 +02:00
break;
}
}
};
function validateRepeatableInput(value, { key, min, max }) {
if (!Array.isArray(value)) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} is repetable. Expected an array`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
value.forEach(val => {
if (typeof val !== 'object' || Array.isArray(val) || val === null) {
const err = new Error(
2019-10-22 18:01:03 +02:00
`Component ${key} as invalid items. Expected each items to be objects`
);
err.status = 400;
throw err;
}
});
2019-07-15 15:33:42 +02:00
if (min && value.length < min) {
2019-10-22 18:01:03 +02:00
const err = new Error(
`Component ${key} must contain at least ${min} items`
);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
if (max && value.length > max) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} must contain at most ${max} items`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
}
function validateNonRepeatableInput(value, { key, required }) {
if (typeof value !== 'object' || Array.isArray(value)) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} should be an object`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
if (required === true && value === null) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} is required`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
}