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

63 lines
1.4 KiB
JavaScript
Raw Normal View History

'use strict';
const { get } = require('lodash/fp');
const { getService } = require('../../utils');
const validateLocaleCreation = async (ctx, next) => {
const { model } = ctx.params;
const { query, body } = ctx.request;
const modelDef = strapi.getModel(model);
if (!isLocalized(modelDef)) {
return next();
}
const { getValidLocale, getNewLocalizationsFor, isLocalized } = getService('content-types');
2021-03-12 19:56:42 +01:00
const locale = get('plugins.i18n.locale', query);
const relatedEntityId = get('plugins.i18n.relatedEntityId', query);
// cleanup to avoid creating duplicates in singletypes
ctx.request.query = {};
let entityLocale;
try {
entityLocale = await getValidLocale(locale);
} catch (e) {
return ctx.badRequest("This locale doesn't exist");
}
2021-03-12 19:56:42 +01:00
body.locale = entityLocale;
if (modelDef.kind === 'singleType') {
const entity = await strapi.entityService.find(
{ params: { _locale: entityLocale } },
{ model }
);
ctx.request.query._locale = body.locale;
2021-03-11 19:40:42 +01:00
// updating
if (entity) {
return next();
2021-03-11 19:40:42 +01:00
}
}
2021-03-11 19:40:42 +01:00
try {
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;