Prune obsolete files relations on startup

Signed-off-by: Convly <jean-sebastien.herbaux@epitech.eu>
This commit is contained in:
Convly 2020-04-30 16:37:18 +02:00
parent ff2dbb3865
commit 079ad89781

View File

@ -1,15 +1,18 @@
'use strict'; 'use strict';
/** /**
* Upload plugin bootstrapi. * Upload plugin bootstrap.
* *
* It initializes the provider and sets the default settings in db. * It initializes the provider and sets the default settings in db.
*/ */
module.exports = async () => { module.exports = async () => {
const type = 'plugin';
const name = 'upload';
// set plugin store // set plugin store
const configurator = strapi.store({ const configurator = strapi.store({
type: 'plugin', type,
name: 'upload', name,
key: 'settings', key: 'settings',
}); });
@ -26,6 +29,8 @@ module.exports = async () => {
}, },
}); });
} }
await pruneObsoleteRelations(name);
}; };
const createProvider = ({ provider, providerOptions }) => { const createProvider = ({ provider, providerOptions }) => {
@ -52,3 +57,23 @@ const baseProvider = {
throw new Error('Provider delete method is not implemented'); throw new Error('Provider delete method is not implemented');
}, },
}; };
const pruneObsoleteRelations = async name => {
const { orm } = strapi.plugins[name].models.file;
if (orm !== 'mongoose') {
return;
}
await strapi.query('file', 'upload').custom(pruneObsoleteRelationsQuery)();
};
const pruneObsoleteRelationsQuery = ({ model }) => {
const models = Array.from(strapi.db.models.values());
const modelsId = models.map(model => model.globalId);
return model.updateMany(
{ related: { $elemMatch: { kind: { $nin: modelsId } } } },
{ $pull: { related: { kind: { $nin: modelsId } } } }
);
};