Add new media lib settings. Remove db provider config

Signed-off-by: Alexandre Bodin <bodin.alex@gmail.com>
This commit is contained in:
Alexandre Bodin 2020-02-26 18:34:45 +01:00
parent 2f307a007e
commit 68fbf77b30
10 changed files with 129 additions and 204 deletions

View File

@ -0,0 +1,36 @@
const bootstrap = require('../bootstrap');
describe('Upload plugin bootstrap function', () => {
test('Sets default config if id does not exist', async () => {
const setStore = jest.fn(() => {});
const strapi = {
config: {
info: {
dependencies: {},
},
},
plugins: {
upload: { config: {} },
},
store() {
return {
get() {
return null;
},
set: setStore,
};
},
};
await bootstrap(strapi);
expect(setStore).toHaveBeenCalledWith({
value: {
sizeOptimization: true,
videoPreview: true,
responsiveDimensions: true,
},
});
});
});

View File

@ -9,15 +9,20 @@
*/ */
const _ = require('lodash'); const _ = require('lodash');
module.exports = async () => { module.exports = async strapi => {
// set plugin store // set plugin store
const pluginStore = strapi.store({ const configurator = strapi.store({
environment: strapi.config.environment,
type: 'plugin', type: 'plugin',
name: 'upload', name: 'upload',
key: 'settings',
}); });
strapi.plugins.upload.config.providers = []; Object.assign(strapi.plugins.upload.config, {
enabled: true,
provider: 'local',
sizeLimit: 1000000,
providers: [],
});
const installedProviders = Object.keys(strapi.config.info.dependencies) const installedProviders = Object.keys(strapi.config.info.dependencies)
.filter(d => d.includes('strapi-provider-upload-')) .filter(d => d.includes('strapi-provider-upload-'))
@ -28,19 +33,15 @@ module.exports = async () => {
} }
// if provider config does not exist set one by default // if provider config does not exist set one by default
const config = await pluginStore.get({ key: 'provider' }); const config = await configurator.get();
if (!config) { if (!config) {
const provider = _.find(strapi.plugins.upload.config.providers, { await configurator.set({
provider: 'local', value: {
sizeOptimization: true,
responsiveDimensions: true,
videoPreview: true,
},
}); });
const value = _.assign({}, provider, {
enabled: true,
// by default limit size to 1 GB
sizeLimit: 1000000,
});
await pluginStore.set({ key: 'provider', value });
} }
}; };

View File

@ -15,15 +15,7 @@
}, },
{ {
"method": "GET", "method": "GET",
"path": "/environments", "path": "/settings",
"handler": "Upload.getEnvironments",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/settings/:environment",
"handler": "Upload.getSettings", "handler": "Upload.getSettings",
"config": { "config": {
"policies": [] "policies": []
@ -31,7 +23,7 @@
}, },
{ {
"method": "PUT", "method": "PUT",
"path": "/settings/:environment", "path": "/settings",
"handler": "Upload.updateSettings", "handler": "Upload.updateSettings",
"config": { "config": {
"policies": [] "policies": []

View File

@ -40,13 +40,7 @@ module.exports = {
resolver: async (obj, { file: upload, ...fields }) => { resolver: async (obj, { file: upload, ...fields }) => {
const file = await formatFile(upload, fields); const file = await formatFile(upload, fields);
const config = await strapi const config = strapi.plugins.upload.config;
.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'upload',
})
.get({ key: 'provider' });
const uploadedFiles = await strapi.plugins.upload.services.upload.upload( const uploadedFiles = await strapi.plugins.upload.services.upload.upload(
[file], [file],
@ -66,13 +60,7 @@ module.exports = {
uploads.map(upload => formatFile(upload, fields)) uploads.map(upload => formatFile(upload, fields))
); );
const config = await strapi const config = strapi.plugins.upload.config;
.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'upload',
})
.get({ key: 'provider' });
const uploadedFiles = await strapi.plugins.upload.services.upload.upload( const uploadedFiles = await strapi.plugins.upload.services.upload.upload(
files, files,

View File

@ -3,17 +3,17 @@
/** /**
* Upload.js controller * Upload.js controller
* *
* @description: A set of functions called "actions" of the `upload` plugin.
*/ */
const _ = require('lodash'); const _ = require('lodash');
const validateSettings = require('./validation/settings');
module.exports = { module.exports = {
async upload(ctx) { async upload(ctx) {
const uploadService = strapi.plugins.upload.services.upload; const uploadService = strapi.plugins.upload.services.upload;
// Retrieve provider configuration. // Retrieve provider configuration.
const config = await uploadService.getConfig(); const config = strapi.plugins.upload.config;
// Verify if the file upload is enable. // Verify if the file upload is enable.
if (config.enabled === false) { if (config.enabled === false) {
@ -98,48 +98,32 @@ module.exports = {
ctx.send(uploadedFiles); ctx.send(uploadedFiles);
}, },
async getEnvironments(ctx) {
const environments = Object.keys(strapi.config.environments).map(
environment => ({
name: environment,
active: strapi.config.environment === environment,
})
);
ctx.send({ environments });
},
async getSettings(ctx) { async getSettings(ctx) {
const config = await strapi const config = await strapi
.store({ .store({
environment: ctx.params.environment,
type: 'plugin', type: 'plugin',
name: 'upload', name: 'upload',
key: 'settings',
}) })
.get({ key: 'provider' }); .get();
ctx.send({ ctx.send({
providers: strapi.plugins.upload.config.providers, data: config,
config,
}); });
}, },
async updateSettings(ctx) { async updateSettings(ctx) {
const { const configurator = strapi.store({
request: { body: newSettings },
} = ctx;
await strapi
.store({
environment: ctx.params.environment,
type: 'plugin', type: 'plugin',
name: 'upload', name: 'upload',
}) key: 'settings',
.set({
key: 'provider',
value: { ...newSettings, sizeLimit: parseFloat(newSettings.sizeLimit) },
}); });
ctx.send({ ok: true }); const data = await validateSettings(ctx.request.body);
await configurator.set({ key: 'settings', value: data });
ctx.body = { data };
}, },
async find(ctx) { async find(ctx) {
@ -173,13 +157,7 @@ module.exports = {
async destroy(ctx) { async destroy(ctx) {
const { id } = ctx.params; const { id } = ctx.params;
const config = await strapi const config = strapi.plugins.upload.config;
.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'upload',
})
.get({ key: 'provider' });
const file = await strapi.plugins['upload'].services.upload.fetch({ id }); const file = await strapi.plugins['upload'].services.upload.fetch({ id });

View File

@ -0,0 +1,23 @@
'use strict';
const { yup, formatYupErrors } = require('strapi-utils');
const settingsSchema = yup.object({
sizeOptimization: yup.boolean().required(),
responsiveDimensions: yup.boolean().required(),
videoPreview: yup.boolean().required(),
});
const validateSettings = data => {
return settingsSchema
.validate(data, {
abortEarly: false,
})
.catch(error => {
throw strapi.errors.badRequest('ValidationError', {
errors: formatYupErrors(error),
});
});
};
module.exports = validateSettings;

View File

@ -139,13 +139,7 @@ module.exports = {
async uploadToEntity(params, files, source) { async uploadToEntity(params, files, source) {
// Retrieve provider settings from database. // Retrieve provider settings from database.
const config = await strapi const config = strapi.plugins.upload.config;
.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'upload',
})
.get({ key: 'provider' });
const model = strapi.getModel(params.model, source); const model = strapi.getModel(params.model, source);

View File

@ -8,85 +8,22 @@ const { createAuthRequest } = require('../../../test/helpers/request');
let rq; let rq;
const defaultProviderConfig = {
provider: 'local',
name: 'Local server',
enabled: true,
sizeLimit: 1000000,
};
const resetProviderConfigToDefault = () => {
return setConfigOptions(defaultProviderConfig);
};
const setConfigOptions = assign => {
return rq.put('/upload/settings/development', {
body: {
...defaultProviderConfig,
...assign,
},
});
};
describe('Upload plugin end to end tests', () => { describe('Upload plugin end to end tests', () => {
beforeAll(async () => { beforeAll(async () => {
const token = await registerAndLogin(); const token = await registerAndLogin();
rq = createAuthRequest(token); rq = createAuthRequest(token);
}, 60000); }, 60000);
afterEach(async () => { describe('GET /upload/settings => Get settings for an environment', () => {
await resetProviderConfigToDefault(); test('Returns the settings', async () => {
}); const res = await rq.get('/upload/settings');
describe('GET /upload/environments => List available environments', () => {
test('Returns the list of envrionments and which one is currently active', async () => {
const res = await rq.get('/upload/environments');
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(200);
expect(res.body).toEqual({ expect(res.body).toEqual({
environments: expect.arrayContaining([ data: {
{ sizeOptimization: true,
name: 'development', videoPreview: true,
active: true, responsiveDimensions: true,
},
{
name: 'staging',
active: false,
},
{
name: 'production',
active: false,
},
]),
});
});
});
describe('GET /upload/settings/:environment => Get settings for an environment', () => {
test('Lists the available providers', async () => {
const res = await rq.get('/upload/settings/development');
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
providers: [
{
provider: 'local',
name: 'Local server',
},
],
});
});
test('Return the default provider config', async () => {
const res = await rq.get('/upload/settings/development');
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
config: {
provider: 'local',
name: 'Local server',
enabled: true,
sizeLimit: 1000000,
}, },
}); });
}); });
@ -94,24 +31,32 @@ describe('Upload plugin end to end tests', () => {
describe('PUT /upload/settings/:environment', () => { describe('PUT /upload/settings/:environment', () => {
test('Updates an envrionment config correctly', async () => { test('Updates an envrionment config correctly', async () => {
const updateRes = await rq.put('/upload/settings/development', { const updateRes = await rq.put('/upload/settings', {
body: { body: {
provider: 'test', sizeOptimization: true,
enabled: false, videoPreview: false,
sizeLimit: 1000, responsiveDimensions: true,
}, },
}); });
expect(updateRes.statusCode).toBe(200); expect(updateRes.statusCode).toBe(200);
expect(updateRes.body).toEqual({ ok: true }); expect(updateRes.body).toEqual({
data: {
sizeOptimization: true,
videoPreview: false,
responsiveDimensions: true,
},
});
const getRes = await rq.get('/upload/settings/development'); const getRes = await rq.get('/upload/settings');
expect(getRes.statusCode).toBe(200); expect(getRes.statusCode).toBe(200);
expect(getRes.body.config).toEqual({ expect(getRes.body).toEqual({
provider: 'test', data: {
enabled: false, sizeOptimization: true,
sizeLimit: 1000, videoPreview: false,
responsiveDimensions: true,
},
}); });
}); });
}); });
@ -142,21 +87,6 @@ describe('Upload plugin end to end tests', () => {
); );
}); });
test('Rejects when provider is not enabled', async () => {
await setConfigOptions({ enabled: false });
const res = await rq.post('/upload', {
formData: {
files: fs.createReadStream(__dirname + '/rec.jpg'),
},
});
expect(res.statusCode).toBe(400);
expect(res.body).toMatchObject({
message: [{ messages: [{ message: 'File upload is disabled' }] }],
});
});
test('Rejects when no files are provided', async () => { test('Rejects when no files are provided', async () => {
const res = await rq.post('/upload', { const res = await rq.post('/upload', {
formData: {}, formData: {},
@ -167,27 +97,6 @@ describe('Upload plugin end to end tests', () => {
message: [{ messages: [{ message: 'Files are empty' }] }], message: [{ messages: [{ message: 'Files are empty' }] }],
}); });
}); });
test('Rejects when any file if over the configured size limit', async () => {
await setConfigOptions({
sizeLimit: 0,
});
const res = await rq.post('/upload', {
formData: {
files: fs.createReadStream(__dirname + '/rec.jpg'),
},
});
expect(res.statusCode).toBe(400);
expect(res.body).toMatchObject({
message: [
{
messages: [{ message: 'rec.jpg file is bigger than limit size!' }],
},
],
});
});
}); });
describe('GET /upload/files => Find files', () => {}); describe('GET /upload/files => Find files', () => {});

View File

@ -471,16 +471,16 @@ class Strapi extends EventEmitter {
this.log.warn('Make sure you call it?'); this.log.warn('Make sure you call it?');
}, timeoutMs); }, timeoutMs);
async function execBootstrap(fn) { const execBootstrap = async fn => {
if (!fn) return; if (!fn) return;
const timer = warnOnTimeout(); const timer = warnOnTimeout();
try { try {
await fn(); await fn(this);
} finally { } finally {
clearTimeout(timer); clearTimeout(timer);
} }
} };
const pluginBoostraps = Object.keys(this.plugins).map(plugin => { const pluginBoostraps = Object.keys(this.plugins).map(plugin => {
return execBootstrap( return execBootstrap(

View File

@ -25,7 +25,11 @@ const loadFiles = async (
} = {} } = {}
) => { ) => {
const root = {}; const root = {};
const files = await glob(pattern, { cwd: dir, ...globArgs }); const files = await glob(pattern, {
cwd: dir,
...globArgs,
ignore: ['**/__tests__/**'],
});
for (let file of files) { for (let file of files) {
const absolutePath = path.resolve(dir, file); const absolutePath = path.resolve(dir, file);