mirror of
https://github.com/strapi/strapi.git
synced 2025-11-13 16:52:18 +00:00
Fix findOne with PK as one of the params
Signed-off-by: Pierre Noël <pierre.noel@strapi.io>
This commit is contained in:
parent
37d6a3464d
commit
c0d9dd26d1
@ -4,11 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const _ = require('lodash');
|
const _ = require('lodash');
|
||||||
const {
|
const { convertRestQueryParams, buildQuery, models: modelUtils } = require('strapi-utils');
|
||||||
convertRestQueryParams,
|
|
||||||
buildQuery,
|
|
||||||
models: modelUtils,
|
|
||||||
} = require('strapi-utils');
|
|
||||||
|
|
||||||
module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
||||||
/* Utils */
|
/* Utils */
|
||||||
@ -50,14 +46,6 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
* Find one entry based on params
|
* Find one entry based on params
|
||||||
*/
|
*/
|
||||||
async function findOne(params, populate, { transacting } = {}) {
|
async function findOne(params, populate, { transacting } = {}) {
|
||||||
const primaryKey = params[model.primaryKey] || params.id;
|
|
||||||
|
|
||||||
if (primaryKey) {
|
|
||||||
params = {
|
|
||||||
[model.primaryKey]: primaryKey,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const entry = await model.where(params).fetch({
|
const entry = await model.where(params).fetch({
|
||||||
withRelated: populate,
|
withRelated: populate,
|
||||||
transacting,
|
transacting,
|
||||||
@ -99,10 +87,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
const entry = await model.forge(data).save(null, { transacting: trx });
|
const entry = await model.forge(data).save(null, { transacting: trx });
|
||||||
await createComponents(entry, values, { transacting: trx });
|
await createComponents(entry, values, { transacting: trx });
|
||||||
|
|
||||||
return model.updateRelations(
|
return model.updateRelations({ id: entry.id, values: relations }, { transacting: trx });
|
||||||
{ id: entry.id, values: relations },
|
|
||||||
{ transacting: trx }
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return wrapTransaction(runCreate, { transacting });
|
return wrapTransaction(runCreate, { transacting });
|
||||||
@ -133,10 +118,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
await updateComponents(updatedEntry, values, { transacting: trx });
|
await updateComponents(updatedEntry, values, { transacting: trx });
|
||||||
|
|
||||||
if (Object.keys(relations).length > 0) {
|
if (Object.keys(relations).length > 0) {
|
||||||
return model.updateRelations(
|
return model.updateRelations({ id: entry.id, values: relations }, { transacting: trx });
|
||||||
{ id: entry.id, values: relations },
|
|
||||||
{ transacting: trx }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.findOne(params, null, { transacting: trx });
|
return this.findOne(params, null, { transacting: trx });
|
||||||
@ -145,8 +127,8 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
return wrapTransaction(runUpdate, { transacting });
|
return wrapTransaction(runUpdate, { transacting });
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteOne(params, { transacting } = {}) {
|
async function deleteOne(id, { transacting } = {}) {
|
||||||
const entry = await model.where(params).fetch({ transacting });
|
const entry = await model.where({ id }).fetch({ transacting });
|
||||||
|
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
const err = new Error('entry.notFound');
|
const err = new Error('entry.notFound');
|
||||||
@ -173,13 +155,11 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
await model.updateRelations({ ...params, values }, { transacting });
|
await model.updateRelations({ [model.primaryKey]: id, values }, { transacting });
|
||||||
|
|
||||||
const runDelete = async trx => {
|
const runDelete = async trx => {
|
||||||
await deleteComponents(entry, { transacting: trx });
|
await deleteComponents(entry, { transacting: trx });
|
||||||
await model
|
await model.where({ id: entry.id }).destroy({ transacting: trx, require: false });
|
||||||
.where({ id: entry.id })
|
|
||||||
.destroy({ transacting: trx, require: false });
|
|
||||||
return entry.toJSON();
|
return entry.toJSON();
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -187,13 +167,9 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function deleteMany(params, { transacting } = {}) {
|
async function deleteMany(params, { transacting } = {}) {
|
||||||
const primaryKey = params[model.primaryKey] || params.id;
|
|
||||||
|
|
||||||
if (primaryKey) return deleteOne(params, { transacting });
|
|
||||||
|
|
||||||
const entries = await find(params, null, { transacting });
|
const entries = await find(params, null, { transacting });
|
||||||
return await Promise.all(
|
return await Promise.all(
|
||||||
entries.map(entry => deleteOne({ id: entry.id }, { transacting }))
|
entries.map(entry => deleteOne(entry[model.primaryKey], { transacting }))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -237,12 +213,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
const joinModel = model.componentsJoinModel;
|
const joinModel = model.componentsJoinModel;
|
||||||
const { foreignKey } = joinModel;
|
const { foreignKey } = joinModel;
|
||||||
|
|
||||||
const createComponentAndLink = async ({
|
const createComponentAndLink = async ({ componentModel, value, key, order }) => {
|
||||||
componentModel,
|
|
||||||
value,
|
|
||||||
key,
|
|
||||||
order,
|
|
||||||
}) => {
|
|
||||||
return strapi
|
return strapi
|
||||||
.query(componentModel.uid)
|
.query(componentModel.uid)
|
||||||
.create(value, { transacting })
|
.create(value, { transacting })
|
||||||
@ -343,12 +314,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
const joinModel = model.componentsJoinModel;
|
const joinModel = model.componentsJoinModel;
|
||||||
const { foreignKey } = joinModel;
|
const { foreignKey } = joinModel;
|
||||||
|
|
||||||
const updateOrCreateComponentAndLink = async ({
|
const updateOrCreateComponentAndLink = async ({ componentModel, key, value, order }) => {
|
||||||
componentModel,
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
order,
|
|
||||||
}) => {
|
|
||||||
// check if value has an id then update else create
|
// check if value has an id then update else create
|
||||||
if (_.has(value, componentModel.primaryKey)) {
|
if (_.has(value, componentModel.primaryKey)) {
|
||||||
return strapi
|
return strapi
|
||||||
@ -481,11 +447,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteDynamicZoneOldComponents(
|
async function deleteDynamicZoneOldComponents(entry, values, { key, joinModel, transacting }) {
|
||||||
entry,
|
|
||||||
values,
|
|
||||||
{ key, joinModel, transacting }
|
|
||||||
) {
|
|
||||||
const idsToKeep = values.reduce((acc, value) => {
|
const idsToKeep = values.reduce((acc, value) => {
|
||||||
const component = value.__component;
|
const component = value.__component;
|
||||||
const componentModel = strapi.components[component];
|
const componentModel = strapi.components[component];
|
||||||
@ -506,8 +468,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
.fetchAll({ transacting })
|
.fetchAll({ transacting })
|
||||||
.map(el => {
|
.map(el => {
|
||||||
const componentKey = Object.keys(strapi.components).find(
|
const componentKey = Object.keys(strapi.components).find(
|
||||||
key =>
|
key => strapi.components[key].collectionName === el.get('component_type')
|
||||||
strapi.components[key].collectionName === el.get('component_type')
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -518,9 +479,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
|
|
||||||
// verify the provided ids are realted to this entity.
|
// verify the provided ids are realted to this entity.
|
||||||
idsToKeep.forEach(({ id, component }) => {
|
idsToKeep.forEach(({ id, component }) => {
|
||||||
if (
|
if (!allIds.find(el => el.id === id && el.component.uid === component.uid)) {
|
||||||
!allIds.find(el => el.id === id && el.component.uid === component.uid)
|
|
||||||
) {
|
|
||||||
const err = new Error(
|
const err = new Error(
|
||||||
`Some of the provided components in ${key} are not related to the entity`
|
`Some of the provided components in ${key} are not related to the entity`
|
||||||
);
|
);
|
||||||
@ -530,11 +489,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const idsToDelete = allIds.reduce((acc, { id, component }) => {
|
const idsToDelete = allIds.reduce((acc, { id, component }) => {
|
||||||
if (
|
if (!idsToKeep.find(el => el.id === id && el.component.uid === component.uid)) {
|
||||||
!idsToKeep.find(
|
|
||||||
el => el.id === id && el.component.uid === component.uid
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
acc.push({
|
acc.push({
|
||||||
id,
|
id,
|
||||||
component,
|
component,
|
||||||
@ -550,10 +505,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
qb.where(qb => {
|
qb.where(qb => {
|
||||||
idsToDelete.forEach(({ id, component }) => {
|
idsToDelete.forEach(({ id, component }) => {
|
||||||
qb.orWhere(qb => {
|
qb.orWhere(qb => {
|
||||||
qb.where('component_id', id).andWhere(
|
qb.where('component_id', id).andWhere('component_type', component.collectionName);
|
||||||
'component_type',
|
|
||||||
component.collectionName
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -573,9 +525,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
componentValue,
|
componentValue,
|
||||||
{ key, joinModel, componentModel, transacting }
|
{ key, joinModel, componentModel, transacting }
|
||||||
) {
|
) {
|
||||||
const componentArr = Array.isArray(componentValue)
|
const componentArr = Array.isArray(componentValue) ? componentValue : [componentValue];
|
||||||
? componentValue
|
|
||||||
: [componentValue];
|
|
||||||
|
|
||||||
const idsToKeep = componentArr
|
const idsToKeep = componentArr
|
||||||
.filter(el => _.has(el, componentModel.primaryKey))
|
.filter(el => _.has(el, componentModel.primaryKey))
|
||||||
@ -603,17 +553,12 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
const idsToDelete = _.difference(allIds, idsToKeep);
|
const idsToDelete = _.difference(allIds, idsToKeep);
|
||||||
if (idsToDelete.length > 0) {
|
if (idsToDelete.length > 0) {
|
||||||
await joinModel
|
await joinModel
|
||||||
.query(qb =>
|
.query(qb => qb.whereIn('component_id', idsToDelete).andWhere('field', key))
|
||||||
qb.whereIn('component_id', idsToDelete).andWhere('field', key)
|
|
||||||
)
|
|
||||||
.destroy({ transacting, require: false });
|
.destroy({ transacting, require: false });
|
||||||
|
|
||||||
await strapi
|
await strapi
|
||||||
.query(componentModel.uid)
|
.query(componentModel.uid)
|
||||||
.delete(
|
.delete({ [`${componentModel.primaryKey}_in`]: idsToDelete }, { transacting });
|
||||||
{ [`${componentModel.primaryKey}_in`]: idsToDelete },
|
|
||||||
{ transacting }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -643,10 +588,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
|
|
||||||
await strapi
|
await strapi
|
||||||
.query(componentModel.uid)
|
.query(componentModel.uid)
|
||||||
.delete(
|
.delete({ [`${componentModel.primaryKey}_in`]: ids }, { transacting });
|
||||||
{ [`${componentModel.primaryKey}_in`]: ids },
|
|
||||||
{ transacting }
|
|
||||||
);
|
|
||||||
|
|
||||||
await joinModel
|
await joinModel
|
||||||
.where({
|
.where({
|
||||||
@ -674,9 +616,7 @@ module.exports = function createQueryBuilder({ model, modelKey, strapi }) {
|
|||||||
const { uid, collectionName } = strapi.components[compo];
|
const { uid, collectionName } = strapi.components[compo];
|
||||||
const model = strapi.query(uid);
|
const model = strapi.query(uid);
|
||||||
|
|
||||||
const toDelete = componentJoins.filter(
|
const toDelete = componentJoins.filter(el => el.componentType === collectionName);
|
||||||
el => el.componentType === collectionName
|
|
||||||
);
|
|
||||||
|
|
||||||
if (toDelete.length > 0) {
|
if (toDelete.length > 0) {
|
||||||
await model.delete(
|
await model.delete(
|
||||||
@ -725,33 +665,18 @@ const buildSearchQuery = (qb, model, params) => {
|
|||||||
const associations = model.associations.map(x => x.alias);
|
const associations = model.associations.map(x => x.alias);
|
||||||
|
|
||||||
const searchText = Object.keys(model._attributes)
|
const searchText = Object.keys(model._attributes)
|
||||||
.filter(
|
.filter(attribute => attribute !== model.primaryKey && !associations.includes(attribute))
|
||||||
attribute =>
|
.filter(attribute => ['string', 'text'].includes(model._attributes[attribute].type));
|
||||||
attribute !== model.primaryKey && !associations.includes(attribute)
|
|
||||||
)
|
|
||||||
.filter(attribute =>
|
|
||||||
['string', 'text'].includes(model._attributes[attribute].type)
|
|
||||||
);
|
|
||||||
|
|
||||||
const searchInt = Object.keys(model._attributes)
|
const searchInt = Object.keys(model._attributes)
|
||||||
.filter(
|
.filter(attribute => attribute !== model.primaryKey && !associations.includes(attribute))
|
||||||
attribute =>
|
|
||||||
attribute !== model.primaryKey && !associations.includes(attribute)
|
|
||||||
)
|
|
||||||
.filter(attribute =>
|
.filter(attribute =>
|
||||||
['integer', 'decimal', 'float'].includes(
|
['integer', 'decimal', 'float'].includes(model._attributes[attribute].type)
|
||||||
model._attributes[attribute].type
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const searchBool = Object.keys(model._attributes)
|
const searchBool = Object.keys(model._attributes)
|
||||||
.filter(
|
.filter(attribute => attribute !== model.primaryKey && !associations.includes(attribute))
|
||||||
attribute =>
|
.filter(attribute => ['boolean'].includes(model._attributes[attribute].type));
|
||||||
attribute !== model.primaryKey && !associations.includes(attribute)
|
|
||||||
)
|
|
||||||
.filter(attribute =>
|
|
||||||
['boolean'].includes(model._attributes[attribute].type)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!_.isNaN(_.toNumber(query))) {
|
if (!_.isNaN(_.toNumber(query))) {
|
||||||
searchInt.forEach(attribute => {
|
searchInt.forEach(attribute => {
|
||||||
@ -768,10 +693,7 @@ const buildSearchQuery = (qb, model, params) => {
|
|||||||
// Search in columns with text using index.
|
// Search in columns with text using index.
|
||||||
switch (model.client) {
|
switch (model.client) {
|
||||||
case 'mysql':
|
case 'mysql':
|
||||||
qb.orWhereRaw(
|
qb.orWhereRaw(`MATCH(${searchText.join(',')}) AGAINST(? IN BOOLEAN MODE)`, `*${query}*`);
|
||||||
`MATCH(${searchText.join(',')}) AGAINST(? IN BOOLEAN MODE)`,
|
|
||||||
`*${query}*`
|
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
case 'pg': {
|
case 'pg': {
|
||||||
const searchQuery = searchText.map(attribute =>
|
const searchQuery = searchText.map(attribute =>
|
||||||
@ -803,13 +725,8 @@ function validateRepeatableInput(value, { key, min, max, required }) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (
|
if ((required === true || (required !== true && value.length > 0)) && min && value.length < min) {
|
||||||
(required === true || (required !== true && value.length > 0)) &&
|
const err = new Error(`Component ${key} must contain at least ${min} items`);
|
||||||
(min && value.length < min)
|
|
||||||
) {
|
|
||||||
const err = new Error(
|
|
||||||
`Component ${key} must contain at least ${min} items`
|
|
||||||
);
|
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@ -835,10 +752,7 @@ function validateNonRepeatableInput(value, { key, required }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateDynamiczoneInput(
|
function validateDynamiczoneInput(value, { key, min, max, components, required }) {
|
||||||
value,
|
|
||||||
{ key, min, max, components, required }
|
|
||||||
) {
|
|
||||||
if (!Array.isArray(value)) {
|
if (!Array.isArray(value)) {
|
||||||
const err = new Error(`Dynamiczone ${key} is invalid. Expected an array`);
|
const err = new Error(`Dynamiczone ${key} is invalid. Expected an array`);
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
@ -869,20 +783,13 @@ function validateDynamiczoneInput(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (
|
if ((required === true || (required !== true && value.length > 0)) && min && value.length < min) {
|
||||||
(required === true || (required !== true && value.length > 0)) &&
|
const err = new Error(`Dynamiczone ${key} must contain at least ${min} items`);
|
||||||
(min && value.length < min)
|
|
||||||
) {
|
|
||||||
const err = new Error(
|
|
||||||
`Dynamiczone ${key} must contain at least ${min} items`
|
|
||||||
);
|
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
if (max && value.length > max) {
|
if (max && value.length > max) {
|
||||||
const err = new Error(
|
const err = new Error(`Dynamiczone ${key} must contain at most ${max} items`);
|
||||||
`Dynamiczone ${key} must contain at most ${max} items`
|
|
||||||
);
|
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,17 +4,12 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const _ = require('lodash');
|
const _ = require('lodash');
|
||||||
const {
|
const { convertRestQueryParams, buildQuery, models: modelUtils } = require('strapi-utils');
|
||||||
convertRestQueryParams,
|
|
||||||
buildQuery,
|
|
||||||
models: modelUtils,
|
|
||||||
} = require('strapi-utils');
|
|
||||||
|
|
||||||
const { findComponentByGlobalId } = require('./utils/helpers');
|
const { findComponentByGlobalId } = require('./utils/helpers');
|
||||||
|
|
||||||
const hasPK = (obj, model) => _.has(obj, model.primaryKey) || _.has(obj, 'id');
|
const hasPK = (obj, model) => _.has(obj, model.primaryKey) || _.has(obj, 'id');
|
||||||
const getPK = (obj, model) =>
|
const getPK = (obj, model) => (_.has(obj, model.primaryKey) ? obj[model.primaryKey] : obj.id);
|
||||||
_.has(obj, model.primaryKey) ? obj[model.primaryKey] : obj.id;
|
|
||||||
|
|
||||||
module.exports = ({ model, modelKey, strapi }) => {
|
module.exports = ({ model, modelKey, strapi }) => {
|
||||||
const assocKeys = model.associations.map(ast => ast.alias);
|
const assocKeys = model.associations.map(ast => ast.alias);
|
||||||
@ -77,9 +72,7 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
validateNonRepeatableInput(componentValue, { key, ...attr });
|
validateNonRepeatableInput(componentValue, { key, ...attr });
|
||||||
if (componentValue === null) continue;
|
if (componentValue === null) continue;
|
||||||
|
|
||||||
const componentEntry = await strapi
|
const componentEntry = await strapi.query(component).create(componentValue);
|
||||||
.query(component)
|
|
||||||
.create(componentValue);
|
|
||||||
entry[key] = [
|
entry[key] = [
|
||||||
{
|
{
|
||||||
kind: componentModel.globalId,
|
kind: componentModel.globalId,
|
||||||
@ -174,9 +167,7 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const components = await Promise.all(
|
const components = await Promise.all(
|
||||||
componentValue.map(value =>
|
componentValue.map(value => updateOrCreateComponent({ componentUID, value }))
|
||||||
updateOrCreateComponent({ componentUID, value })
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
const componentsArr = components.map(component => ({
|
const componentsArr = components.map(component => ({
|
||||||
kind: componentModel.globalId,
|
kind: componentModel.globalId,
|
||||||
@ -222,14 +213,12 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
const dynamiczones = await Promise.all(
|
const dynamiczones = await Promise.all(
|
||||||
dynamiczoneValues.map(value => {
|
dynamiczoneValues.map(value => {
|
||||||
const componentUID = value.__component;
|
const componentUID = value.__component;
|
||||||
return updateOrCreateComponent({ componentUID, value }).then(
|
return updateOrCreateComponent({ componentUID, value }).then(entity => {
|
||||||
entity => {
|
|
||||||
return {
|
return {
|
||||||
componentUID,
|
componentUID,
|
||||||
entity,
|
entity,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
);
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -273,9 +262,7 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
|
|
||||||
// verify the provided ids are realted to this entity.
|
// verify the provided ids are realted to this entity.
|
||||||
idsToKeep.forEach(({ id, componentUID }) => {
|
idsToKeep.forEach(({ id, componentUID }) => {
|
||||||
if (
|
if (!allIds.find(el => el.id === id && el.componentUID === componentUID)) {
|
||||||
!allIds.find(el => el.id === id && el.componentUID === componentUID)
|
|
||||||
) {
|
|
||||||
const err = new Error(
|
const err = new Error(
|
||||||
`Some of the provided components in ${key} are not related to the entity`
|
`Some of the provided components in ${key} are not related to the entity`
|
||||||
);
|
);
|
||||||
@ -285,9 +272,7 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const idsToDelete = allIds.reduce((acc, { id, componentUID }) => {
|
const idsToDelete = allIds.reduce((acc, { id, componentUID }) => {
|
||||||
if (
|
if (!idsToKeep.find(el => el.id === id && el.componentUID === componentUID)) {
|
||||||
!idsToKeep.find(el => el.id === id && el.componentUID === componentUID)
|
|
||||||
) {
|
|
||||||
acc.push({
|
acc.push({
|
||||||
id,
|
id,
|
||||||
componentUID,
|
componentUID,
|
||||||
@ -317,14 +302,8 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteOldComponents(
|
async function deleteOldComponents(entry, componentValue, { key, componentModel }) {
|
||||||
entry,
|
const componentArr = Array.isArray(componentValue) ? componentValue : [componentValue];
|
||||||
componentValue,
|
|
||||||
{ key, componentModel }
|
|
||||||
) {
|
|
||||||
const componentArr = Array.isArray(componentValue)
|
|
||||||
? componentValue
|
|
||||||
: [componentValue];
|
|
||||||
|
|
||||||
const idsToKeep = componentArr
|
const idsToKeep = componentArr
|
||||||
.filter(val => hasPK(val, componentModel))
|
.filter(val => hasPK(val, componentModel))
|
||||||
@ -352,9 +331,7 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (idsToDelete.length > 0) {
|
if (idsToDelete.length > 0) {
|
||||||
await strapi
|
await strapi.query(componentModel.uid).delete({ [`${model.primaryKey}_in`]: idsToDelete });
|
||||||
.query(componentModel.uid)
|
|
||||||
.delete({ [`${model.primaryKey}_in`]: idsToDelete });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -415,23 +392,11 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
model,
|
model,
|
||||||
filters,
|
filters,
|
||||||
populate: populateOpt,
|
populate: populateOpt,
|
||||||
}).then(results =>
|
}).then(results => results.map(result => (result ? result.toObject() : null)));
|
||||||
results.map(result => (result ? result.toObject() : null))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function findOne(params, populate) {
|
async function findOne(params, populate) {
|
||||||
const primaryKey = getPK(params, model);
|
const entry = await model.findOne(params).populate(populate || defaultPopulate);
|
||||||
|
|
||||||
if (primaryKey) {
|
|
||||||
params = {
|
|
||||||
[model.primaryKey]: primaryKey,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const entry = await model
|
|
||||||
.findOne(params)
|
|
||||||
.populate(populate || defaultPopulate);
|
|
||||||
|
|
||||||
return entry ? entry.toObject() : null;
|
return entry ? entry.toObject() : null;
|
||||||
}
|
}
|
||||||
@ -463,14 +428,6 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function update(params, values) {
|
async function update(params, values) {
|
||||||
const primaryKey = getPK(params, model);
|
|
||||||
|
|
||||||
if (primaryKey) {
|
|
||||||
params = {
|
|
||||||
[model.primaryKey]: primaryKey,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const entry = await model.findOne(params);
|
const entry = await model.findOne(params);
|
||||||
|
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
@ -498,12 +455,12 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
if (primaryKey) return deleteOne(params);
|
if (primaryKey) return deleteOne(params);
|
||||||
|
|
||||||
const entries = await find(params);
|
const entries = await find(params);
|
||||||
return await Promise.all(entries.map(entry => deleteOne({ id: entry.id })));
|
return Promise.all(entries.map(entry => deleteOne(entry[model.primaryKey])));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteOne(params) {
|
async function deleteOne(id) {
|
||||||
const entry = await model
|
const entry = await model
|
||||||
.findOneAndRemove({ [model.primaryKey]: getPK(params, model) })
|
.findOneAndRemove({ [model.primaryKey]: id })
|
||||||
.populate(defaultPopulate);
|
.populate(defaultPopulate);
|
||||||
|
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
@ -521,21 +478,17 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const search =
|
const search =
|
||||||
_.endsWith(association.nature, 'One') ||
|
_.endsWith(association.nature, 'One') || association.nature === 'oneToMany'
|
||||||
association.nature === 'oneToMany'
|
|
||||||
? { [association.via]: entry._id }
|
? { [association.via]: entry._id }
|
||||||
: { [association.via]: { $in: [entry._id] } };
|
: { [association.via]: { $in: [entry._id] } };
|
||||||
const update =
|
const update =
|
||||||
_.endsWith(association.nature, 'One') ||
|
_.endsWith(association.nature, 'One') || association.nature === 'oneToMany'
|
||||||
association.nature === 'oneToMany'
|
|
||||||
? { [association.via]: null }
|
? { [association.via]: null }
|
||||||
: { $pull: { [association.via]: entry._id } };
|
: { $pull: { [association.via]: entry._id } };
|
||||||
|
|
||||||
// Retrieve model.
|
// Retrieve model.
|
||||||
const model = association.plugin
|
const model = association.plugin
|
||||||
? strapi.plugins[association.plugin].models[
|
? strapi.plugins[association.plugin].models[association.model || association.collection]
|
||||||
association.model || association.collection
|
|
||||||
]
|
|
||||||
: strapi.models[association.model || association.collection];
|
: strapi.models[association.model || association.collection];
|
||||||
|
|
||||||
return model.updateMany(search, update);
|
return model.updateMany(search, update);
|
||||||
@ -557,9 +510,7 @@ module.exports = ({ model, modelKey, strapi }) => {
|
|||||||
.skip(filters.start)
|
.skip(filters.start)
|
||||||
.limit(filters.limit)
|
.limit(filters.limit)
|
||||||
.populate(populate || defaultPopulate)
|
.populate(populate || defaultPopulate)
|
||||||
.then(results =>
|
.then(results => results.map(result => (result ? result.toObject() : null)));
|
||||||
results.map(result => (result ? result.toObject() : null))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function countSearch(params) {
|
function countSearch(params) {
|
||||||
@ -623,13 +574,8 @@ function validateRepeatableInput(value, { key, min, max, required }) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (
|
if ((required === true || (required !== true && value.length > 0)) && min && value.length < min) {
|
||||||
(required === true || (required !== true && value.length > 0)) &&
|
const err = new Error(`Component ${key} must contain at least ${min} items`);
|
||||||
(min && value.length < min)
|
|
||||||
) {
|
|
||||||
const err = new Error(
|
|
||||||
`Component ${key} must contain at least ${min} items`
|
|
||||||
);
|
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@ -655,10 +601,7 @@ function validateNonRepeatableInput(value, { key, required }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateDynamiczoneInput(
|
function validateDynamiczoneInput(value, { key, min, max, components, required }) {
|
||||||
value,
|
|
||||||
{ key, min, max, components, required }
|
|
||||||
) {
|
|
||||||
if (!Array.isArray(value)) {
|
if (!Array.isArray(value)) {
|
||||||
const err = new Error(`Dynamiczone ${key} is invalid. Expected an array`);
|
const err = new Error(`Dynamiczone ${key} is invalid. Expected an array`);
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
@ -689,20 +632,13 @@ function validateDynamiczoneInput(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (
|
if ((required === true || (required !== true && value.length > 0)) && min && value.length < min) {
|
||||||
(required === true || (required !== true && value.length > 0)) &&
|
const err = new Error(`Dynamiczone ${key} must contain at least ${min} items`);
|
||||||
(min && value.length < min)
|
|
||||||
) {
|
|
||||||
const err = new Error(
|
|
||||||
`Dynamiczone ${key} must contain at least ${min} items`
|
|
||||||
);
|
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
if (max && value.length > max) {
|
if (max && value.length > max) {
|
||||||
const err = new Error(
|
const err = new Error(`Dynamiczone ${key} must contain at most ${max} items`);
|
||||||
`Dynamiczone ${key} must contain at most ${max} items`
|
|
||||||
);
|
|
||||||
err.status = 400;
|
err.status = 400;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
|
const { replaceIdByPrimaryKey } = require('../utils/primary-key');
|
||||||
|
|
||||||
module.exports = function createQuery(opts) {
|
module.exports = function createQuery(opts) {
|
||||||
return new Query(opts);
|
return new Query(opts);
|
||||||
};
|
};
|
||||||
@ -35,43 +37,49 @@ class Query {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (typeof mapping[this.orm] !== 'function') {
|
if (typeof mapping[this.orm] !== 'function') {
|
||||||
throw new Error(
|
throw new Error(`Custom queries must be functions received ${typeof mapping[this.orm]}`);
|
||||||
`Custom queries must be functions received ${typeof mapping[this.orm]}`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return mapping[this.model.orm].call(this, { model: this.model });
|
return mapping[this.model.orm].call(this, { model: this.model });
|
||||||
}
|
}
|
||||||
|
|
||||||
find(...args) {
|
find(params = {}, ...args) {
|
||||||
return this.connectorQuery.find(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.find(newParams, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
findOne(...args) {
|
findOne(params = {}, ...args) {
|
||||||
return this.connectorQuery.findOne(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.findOne(newParams, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
create(...args) {
|
create(params = {}, ...args) {
|
||||||
return this.connectorQuery.create(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.create(newParams, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
update(...args) {
|
update(params = {}, ...args) {
|
||||||
return this.connectorQuery.update(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.update(newParams, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
delete(...args) {
|
delete(params = {}, ...args) {
|
||||||
return this.connectorQuery.delete(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.delete(newParams, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
count(...args) {
|
count(params = {}, ...args) {
|
||||||
return this.connectorQuery.count(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.count(newParams, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
search(...args) {
|
search(params = {}, ...args) {
|
||||||
return this.connectorQuery.search(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.search(newParams, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
countSearch(...args) {
|
countSearch(params = {}, ...args) {
|
||||||
return this.connectorQuery.countSearch(...args);
|
const newParams = replaceIdByPrimaryKey(params, this.model);
|
||||||
|
return this.connectorQuery.countSearch(newParams, ...args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
14
packages/strapi-database/lib/utils/primary-key.js
Normal file
14
packages/strapi-database/lib/utils/primary-key.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const _ = require('lodash');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
replaceIdByPrimaryKey: (params, model) => {
|
||||||
|
const newParams = { ...params };
|
||||||
|
if (_.has(params, 'id')) {
|
||||||
|
delete newParams.id;
|
||||||
|
newParams[model.primaryKey] = params[model.primaryKey] || params.id;
|
||||||
|
}
|
||||||
|
return newParams;
|
||||||
|
},
|
||||||
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user