strapi/packages/plugins/i18n/server/controllers/validate-locale-creation.js

67 lines
1.7 KiB
JavaScript
Raw Normal View History

'use strict';
const { get } = require('lodash/fp');
2021-10-20 17:30:05 +02:00
const { ApplicationError } = require('@strapi/utils').errors;
2021-06-08 10:39:45 +02:00
const { getService } = require('../utils');
const validateLocaleCreation = async (ctx, next) => {
const { model } = ctx.params;
const { query, body } = ctx.request;
const {
getValidLocale,
getNewLocalizationsFrom,
isLocalizedContentType,
getAndValidateRelatedEntity,
fillNonLocalizedAttributes,
} = getService('content-types');
2021-03-16 17:33:10 +01:00
const modelDef = strapi.getModel(model);
if (!isLocalizedContentType(modelDef)) {
return next();
}
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) {
2021-10-20 17:30:05 +02:00
throw new ApplicationError("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.findMany(modelDef.uid, { locale: entityLocale });
2021-07-19 16:47:24 +02:00
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
let relatedEntity;
try {
relatedEntity = await getAndValidateRelatedEntity(relatedEntityId, model, entityLocale);
} catch (e) {
2021-10-20 17:30:05 +02:00
throw new ApplicationError(
"The related entity doesn't exist or the entity already exists in this locale"
);
}
fillNonLocalizedAttributes(body, relatedEntity, { model });
const localizations = await getNewLocalizationsFrom(relatedEntity);
body.localizations = localizations;
return next();
};
module.exports = validateLocaleCreation;