79 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-02-20 15:57:34 +01:00
'use strict';
/**
* Upload plugin bootstrap.
2018-02-20 15:57:34 +01:00
*
* It initializes the provider and sets the default settings in db.
2018-02-20 15:57:34 +01:00
*/
module.exports = async () => {
const name = 'upload';
2018-02-21 17:18:33 +01:00
// set plugin store
const configurator = strapi.store({
type: 'plugin',
name,
key: 'settings',
2018-02-20 15:57:34 +01:00
});
strapi.plugins.upload.provider = createProvider(strapi.plugins.upload.config || {});
2019-08-12 15:35:40 +02:00
// if provider config does not exist set one by default
const config = await configurator.get();
2019-08-12 15:35:40 +02:00
if (!config) {
await configurator.set({
value: {
sizeOptimization: true,
responsiveDimensions: true,
},
2019-08-12 15:35:40 +02:00
});
2019-04-05 16:11:09 +02:00
}
await pruneObsoleteRelations(name);
2018-02-20 15:57:34 +01:00
};
const createProvider = ({ provider, providerOptions }) => {
try {
const providerInstance = require(`strapi-provider-upload-${provider}`).init(providerOptions);
return Object.assign(Object.create(baseProvider), providerInstance);
} catch (err) {
strapi.log.error(err);
throw new Error(
`The provider package isn't installed. Please run \`npm install strapi-provider-upload-${provider}\``
);
}
};
const baseProvider = {
extend(obj) {
Object.assign(this, obj);
},
upload() {
throw new Error('Provider upload method is not implemented');
},
delete() {
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 } } } }
);
};