220 lines
5.2 KiB
JavaScript
Raw Normal View History

'use strict';
/**
* Upload.js controller
*
*/
2018-02-21 14:06:57 +01:00
const _ = require('lodash');
const validateSettings = require('./validation/settings');
const { yup, formatYupErrors } = require('strapi-utils');
const fileInfoSchema = yup.object({
name: yup.string().nullable(),
alternativeText: yup.string().nullable(),
caption: yup.string().nullable(),
});
const uploadSchema = yup.object({
fileInfo: fileInfoSchema,
});
const multiUploadSchema = yup.object({
fileInfo: yup.array().of(fileInfoSchema),
});
const validateUploadBody = (schema, data = {}) => {
return schema.validate(data, { abortEarly: false }).catch(err => {
throw strapi.errors.badRequest('ValidationError', { errors: formatYupErrors(err) });
});
};
2018-02-21 14:06:57 +01:00
module.exports = {
async upload(ctx) {
2019-08-01 07:48:52 +02:00
const uploadService = strapi.plugins.upload.services.upload;
2018-02-27 16:53:06 +01:00
// Retrieve provider configuration.
const { enabled } = strapi.plugins.upload.config;
2018-02-20 17:10:25 +01:00
2018-02-27 16:53:06 +01:00
// Verify if the file upload is enable.
if (enabled === false) {
throw strapi.errors.badRequest(null, {
errors: [{ id: 'Upload.status.disabled', message: 'File upload is disabled' }],
});
2018-02-20 17:10:25 +01:00
}
const files = _.get(ctx.request.files, 'files');
if (_.isEmpty(files)) {
throw strapi.errors.badRequest(null, {
errors: [{ id: 'Upload.status.empty', message: 'Files are empty' }],
});
}
2018-02-27 16:53:06 +01:00
let data;
if (Array.isArray(files)) {
data = await validateUploadBody(multiUploadSchema, ctx.request.body);
} else {
data = await validateUploadBody(uploadSchema, ctx.request.body);
2018-02-21 14:46:10 +01:00
}
const { refId, ref, source, field, path, fileInfo } = data;
const fileArray = Array.isArray(files) ? files : [files];
const fileInfoArray = Array.isArray(fileInfo) ? fileInfo : [fileInfo];
// Transform stream files to buffer
const enhancedFiles = await Promise.all(
fileArray.map((file, idx) => {
const fileInfo = fileInfoArray[idx] || {};
return uploadService.enhanceFile(file, fileInfo, { refId, ref, source, field, path });
})
);
const uploadedFiles = await uploadService.upload(enhancedFiles);
// Send 200 `ok`
2019-12-24 17:49:17 +01:00
ctx.send(uploadedFiles);
},
async getSettings(ctx) {
const config = await strapi
.store({
type: 'plugin',
name: 'upload',
key: 'settings',
})
.get();
2018-02-20 17:10:25 +01:00
ctx.send({
data: config,
2018-02-20 17:10:25 +01:00
});
},
async updateSettings(ctx) {
const configurator = strapi.store({
type: 'plugin',
name: 'upload',
key: 'settings',
});
const data = await validateSettings(ctx.request.body);
2018-02-20 17:10:25 +01:00
await configurator.set({ key: 'settings', value: data });
ctx.body = { data };
2018-02-20 17:10:25 +01:00
},
async replaceFile(ctx) {
const { id } = ctx.params;
const uploadService = strapi.plugins.upload.services.upload;
// Retrieve provider configuration.
const { enabled } = strapi.plugins.upload.config;
// Verify if the file upload is enable.
if (enabled === false) {
throw strapi.errors.badRequest(null, {
errors: [{ id: 'Upload.status.disabled', message: 'File upload is disabled' }],
});
}
const data = await strapi.plugins['upload'].services.upload.fetch({ id });
if (!data) {
return ctx.notFound('file.notFound');
}
const { fileInfo } = await validateUploadBody(uploadSchema, ctx.request.body);
const { file = {} } = ctx.request.files || {};
if (_.isUndefined(file)) {
throw strapi.errors.badRequest(null, {
errors: [{ id: 'Upload.status.empty', message: 'File is missing' }],
});
}
const enhancedFile = uploadService.enhanceFile(file, fileInfo);
const updatedFile = await uploadService.update(id, enhancedFile);
ctx.send(updatedFile);
},
async find(ctx) {
const data = await strapi.plugins['upload'].services.upload.fetchAll(ctx.query);
// Send 200 `ok`
2019-12-24 17:49:17 +01:00
ctx.send(data);
},
2018-02-19 16:00:37 +01:00
async findOne(ctx) {
const data = await strapi.plugins['upload'].services.upload.fetch(ctx.params);
if (!data) {
return ctx.notFound('file.notFound');
}
ctx.send(data);
},
async count(ctx) {
const data = await strapi.plugins['upload'].services.upload.count(ctx.query);
2018-02-19 19:54:45 +01:00
ctx.send({ count: data });
2018-02-19 19:54:45 +01:00
},
async destroy(ctx) {
const { id } = ctx.params;
2018-02-20 17:10:25 +01:00
const file = await strapi.plugins['upload'].services.upload.fetch({ id });
2018-02-19 16:00:37 +01:00
if (!file) {
return ctx.notFound('file.notFound');
}
await strapi.plugins['upload'].services.upload.remove(file);
ctx.send(file);
2018-02-22 17:12:03 +01:00
},
async search(ctx) {
const { id } = ctx.params;
const data = await strapi.query('file', 'upload').custom(searchQueries)({
id,
});
2018-02-22 17:12:03 +01:00
ctx.send(data);
},
};
const searchQueries = {
bookshelf({ model }) {
return ({ id }) => {
return model
.query(qb => {
qb.whereRaw('LOWER(hash) LIKE ?', [`%${id}%`]).orWhereRaw('LOWER(name) LIKE ?', [
`%${id}%`,
]);
})
.fetchAll()
.then(results => results.toJSON());
};
},
mongoose({ model }) {
return ({ id }) => {
const re = new RegExp(id, 'i');
2019-12-24 17:49:17 +01:00
return model
.find({
$or: [{ hash: re }, { name: re }],
})
.lean();
};
},
};