101 lines
2.4 KiB
JavaScript
Raw Normal View History

'use strict';
/**
* Upload.js controller
*
*/
2018-02-21 14:06:57 +01:00
const _ = require('lodash');
const apiUploadController = require('./upload/api');
const adminUploadController = require('./upload/admin');
const resolveController = ctx => {
const {
state: { isAuthenticatedAdmin },
} = ctx;
return isAuthenticatedAdmin ? adminUploadController : apiUploadController;
};
const resolveControllerMethod = method => ctx => {
const controller = resolveController(ctx);
const callbackFn = controller[method];
if (!_.isFunction(callbackFn)) {
return ctx.notFound();
}
return callbackFn(ctx);
};
module.exports = {
find: resolveControllerMethod('find'),
findOne: resolveControllerMethod('findOne'),
count: resolveControllerMethod('count'),
destroy: resolveControllerMethod('destroy'),
updateSettings: resolveControllerMethod('updateSettings'),
getSettings: resolveControllerMethod('getSettings'),
async upload(ctx) {
const isUploadDisabled = _.get(strapi.plugins, 'upload.config.enabled', true) === false;
if (isUploadDisabled) {
throw strapi.errors.badRequest(null, {
errors: [{ id: 'Upload.status.disabled', message: 'File upload is disabled' }],
});
2018-02-20 17:10:25 +01:00
}
const {
query: { id },
request: { files: { files } = {} },
} = ctx;
const controller = resolveController(ctx);
if (id && (_.isEmpty(files) || files.size === 0)) {
return controller.updateFileInfo(ctx);
}
if (_.isEmpty(files) || files.size === 0) {
throw strapi.errors.badRequest(null, {
errors: [{ id: 'Upload.status.empty', message: 'Files are empty' }],
});
2018-02-21 14:46:10 +01:00
}
await (id ? controller.replaceFile : controller.uploadFiles)(ctx);
2018-02-20 17:10:25 +01:00
},
async search(ctx) {
const { id } = ctx.params;
ctx.body = await strapi.query('file', 'upload').custom(searchQueries)({
id,
});
2018-02-22 17:12:03 +01:00
},
};
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();
};
},
};