86 lines
1.9 KiB
JavaScript
Raw Normal View History

const _ = require('lodash');
module.exports = async (ctx, next) => {
const { source } = ctx.request.query;
const target = source === 'admin' ? strapi.admin : strapi.plugins[source];
if (
source &&
_.get(target, [
'config',
'layout',
ctx.params.model,
'actions',
ctx.request.route.action,
])
) {
const [controller, action] = _.get(
target,
[
'config',
'layout',
ctx.params.model,
'actions',
ctx.request.route.action,
],
[],
).split('.');
if (controller && action) {
// Redirect to specific controller.
if (
ctx.request.body.hasOwnProperty('fields') &&
ctx.request.body.hasOwnProperty('files')
) {
let { files, fields } = ctx.request.body;
2018-03-15 11:51:40 +01:00
const parser = value => {
2018-03-15 11:51:40 +01:00
try {
value = JSON.parse(value);
} catch (e) {
// Silent.
}
return _.isArray(value) ? value.map(obj => parser(obj)) : value;
};
fields = Object.keys(fields).reduce((acc, current) => {
acc[current] = parser(fields[current]);
2018-03-13 15:57:41 +01:00
return acc;
2018-03-15 11:51:40 +01:00
}, {});
2018-03-13 15:57:41 +01:00
2018-03-15 11:51:40 +01:00
ctx.request.body = fields;
2018-03-13 15:57:41 +01:00
await target.controllers[controller.toLowerCase()][action](ctx);
2018-03-15 12:01:10 +01:00
const resBody = ctx.body;
2018-03-13 15:57:41 +01:00
await Promise.all(
Object.keys(files).map(async field => {
ctx.request.body = {
files: {
files: files[field],
},
fields: {
refId: resBody.id || resBody._id,
ref: ctx.params.model,
source,
field,
},
};
return strapi.plugins.upload.controllers.upload.upload(ctx);
}),
);
2018-03-15 11:51:40 +01:00
2018-03-13 15:57:41 +01:00
return ctx.send(resBody);
}
2018-03-15 11:51:40 +01:00
return await target.controllers[controller.toLowerCase()][action](ctx);
}
}
await next();
};