strapi/packages/strapi-plugin-i18n/config/policies/validateLocaleCreation.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

'use strict';
2021-03-11 19:40:42 +01:00
const { get, pick } = require('lodash/fp');
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-11 19:40:42 +01:00
if (isLocalized(modelDef)) {
try {
2021-03-11 19:40:42 +01:00
await addLocale(body, locale);
} 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();
}
}
try {
2021-03-11 19:40:42 +01:00
const localizations = await getNewLocalizationsFor({
relatedEntityId,
model,
locale: body.locale,
});
body.localizations = localizations;
} catch (e) {
return ctx.badRequest(
"The related entity doesn't exist or the entity already exists in this locale"
);
}
}
return next();
};
module.exports = validateLocaleCreation;