2021-03-08 15:39:09 +01:00
|
|
|
'use strict';
|
|
|
|
|
2021-03-11 19:40:42 +01:00
|
|
|
const { get, pick } = require('lodash/fp');
|
2021-03-08 15:39:09 +01:00
|
|
|
const { getService } = require('../../utils');
|
|
|
|
|
|
|
|
const validateLocaleCreation = async (ctx, next) => {
|
|
|
|
const { model } = ctx.params;
|
|
|
|
const { query, body } = ctx.request;
|
|
|
|
|
2021-03-12 19:56:42 +01:00
|
|
|
const locale = get('plugins.i18n.locale', query);
|
|
|
|
const relatedEntityId = get('plugins.i18n.relatedEntityId', query);
|
|
|
|
ctx.request.query = pick(ctx.request.query, 'plugins');
|
|
|
|
|
2021-03-11 19:40:42 +01:00
|
|
|
const { addLocale, getNewLocalizationsFor, isLocalized } = getService('content-types');
|
|
|
|
const modelDef = strapi.getModel(model);
|
2021-03-08 15:39:09 +01:00
|
|
|
|
2021-03-11 19:40:42 +01:00
|
|
|
if (isLocalized(modelDef)) {
|
2021-03-08 15:39:09 +01:00
|
|
|
try {
|
2021-03-11 19:40:42 +01:00
|
|
|
await addLocale(body, locale);
|
2021-03-08 15:39:09 +01:00
|
|
|
} catch (e) {
|
|
|
|
return ctx.badRequest("This locale doesn't exist");
|
|
|
|
}
|
|
|
|
|
2021-03-11 19:40:42 +01:00
|
|
|
if (modelDef.kind === 'singleType') {
|
|
|
|
const entity = await strapi.entityService.find(
|
|
|
|
{ params: { _locale: body.locale } },
|
|
|
|
{ model }
|
|
|
|
);
|
2021-03-12 19:56:42 +01:00
|
|
|
ctx.request.query._locale = body.locale;
|
2021-03-11 19:40:42 +01:00
|
|
|
|
|
|
|
if (entity) {
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-08 15:39:09 +01:00
|
|
|
try {
|
2021-03-11 19:40:42 +01:00
|
|
|
const localizations = await getNewLocalizationsFor({
|
|
|
|
relatedEntityId,
|
|
|
|
model,
|
|
|
|
locale: body.locale,
|
|
|
|
});
|
|
|
|
body.localizations = localizations;
|
2021-03-08 15:39:09 +01:00
|
|
|
} catch (e) {
|
|
|
|
return ctx.badRequest(
|
|
|
|
"The related entity doesn't exist or the entity already exists in this locale"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return next();
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = validateLocaleCreation;
|