75 lines
2.3 KiB
JavaScript
Raw Normal View History

2021-02-15 11:24:28 +01:00
'use strict';
const { pick, isNil } = require('lodash/fp');
const { getService } = require('../utils');
2021-02-15 11:24:28 +01:00
const { getNonLocalizedFields } = require('./content-types');
/**
* Adds the default locale to an object if it isn't defined set yet
* @param {Object} data a data object before being persisted into db
*/
const assignDefaultLocale = async data => {
if (isNil(data.locale)) {
data.locale = await getService('locales').getDefaultLocale();
}
};
/**
* Create default localizations for an entry if it isn't defined yet
* @param {Object} entry entry to update
* @param {Object} options
* @param {Object} options.model corresponding model
*/
2021-02-15 11:24:28 +01:00
const addLocalizations = async (entry, { model }) => {
if (isNil(entry.localizations)) {
const localizations = [{ locale: entry.locale, id: entry.id }];
await strapi.query(model.uid).update({ id: entry.id }, { localizations });
Object.assign(entry, { localizations });
}
};
/**
* Update non localized fields of all the related localizations of an entry with the entry values
* @param {Object} entry entry to update
* @param {Object} options
* @param {Object} options.model corresponding model
*/
2021-02-15 11:24:28 +01:00
const updateNonLocalizedFields = async (entry, { model }) => {
if (Array.isArray(entry.localizations)) {
const fieldsToUpdate = pick(getNonLocalizedFields(model), entry);
2021-02-16 12:23:51 +01:00
const updateQueries = entry.localizations
2021-02-15 11:24:28 +01:00
.filter(({ id }) => id != entry.id)
.map(({ id }) => strapi.query(model.uid).update({ id }, fieldsToUpdate));
2021-02-16 12:23:51 +01:00
await Promise.all(updateQueries);
2021-02-15 11:24:28 +01:00
}
};
/**
* Remove entry from localizations & udpate realted localizations
* @param {Object} entry entry to remove from localizations
* @param {Object} options
* @param {Object} options.model corresponding model
*/
const removeEntryFromLocalizations = async (entry, { model }) => {
if (Array.isArray(entry.localizations)) {
const newLocalizations = entry.localizations.filter(({ id }) => id != entry.id);
const updateQueries = newLocalizations.map(({ id }) => {
return strapi.query(model.uid).update({ id }, { localizations: newLocalizations });
});
await Promise.all(updateQueries);
}
};
2021-02-15 11:24:28 +01:00
module.exports = {
assignDefaultLocale,
2021-02-15 11:24:28 +01:00
addLocalizations,
updateNonLocalizedFields,
removeEntryFromLocalizations,
2021-02-15 11:24:28 +01:00
};