2017-11-29 15:00:50 +01:00
|
|
|
const _ = require('lodash');
|
|
|
|
|
|
|
|
module.exports = async (ctx, next) => {
|
|
|
|
const { source } = ctx.request.query;
|
|
|
|
|
2019-04-09 12:09:03 +02:00
|
|
|
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('.');
|
2017-11-29 15:00:50 +01:00
|
|
|
|
2017-11-29 16:10:13 +01:00
|
|
|
if (controller && action) {
|
|
|
|
// Redirect to specific controller.
|
2019-04-09 12:09:03 +02:00
|
|
|
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
|
|
|
|
2019-04-09 12:09:03 +02: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
|
|
|
|
2019-04-09 12:09:03 +02: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
|
|
|
|
2019-04-09 12:09:03 +02: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
|
|
|
|
2019-04-09 12:09:03 +02:00
|
|
|
return await target.controllers[controller.toLowerCase()][action](ctx);
|
2017-11-29 16:10:13 +01:00
|
|
|
}
|
2017-11-29 15:00:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
await next();
|
|
|
|
};
|