68 lines
2.0 KiB
JavaScript
Raw Normal View History

2021-03-02 17:09:35 +01:00
'use strict';
2021-03-15 18:51:32 +01:00
const { orderBy } = require('lodash/fp');
2021-03-11 10:41:35 +01:00
const { shouldBeProcessed, getUpdatesInfo } = require('./utils');
2021-03-02 17:09:35 +01:00
const BATCH_SIZE = 1000;
2021-03-15 18:51:32 +01:00
const getSortedLocales = async () => {
let defaultLocale;
try {
const defaultLocaleRow = await strapi.models['core_store'].findOne({
key: 'plugin_i18n_default_locale',
});
defaultLocale = JSON.parse(defaultLocaleRow.value);
} catch (e) {
throw new Error("Could not migrate because the default locale doesn't exist");
}
let locales;
try {
strapi.models;
locales = await strapi.plugins.i18n.models.locale.find();
} catch (e) {
throw new Error('Could not migrate because no locale exist');
}
locales.forEach(locale => (locale.isDefault = locale.code === defaultLocale));
return orderBy(['isDefault', 'code'], ['desc', 'asc'])(locales); // Put default locale first
};
const migrateForMongoose = async ({ model, attributesToMigrate }) => {
const locales = await getSortedLocales();
2021-03-02 17:09:35 +01:00
const processedLocaleCodes = [];
for (const locale of locales) {
let batchCount = BATCH_SIZE;
let lastId;
while (batchCount === BATCH_SIZE) {
const findParams = { locale: locale.code };
if (lastId) {
findParams._id = { $gt: lastId };
}
const batch = await model
.find(findParams, [...attributesToMigrate, 'locale', 'localizations'])
2021-03-11 10:41:35 +01:00
.populate('localizations', 'locale id')
2021-03-02 17:09:35 +01:00
.sort({ _id: 1 })
.limit(BATCH_SIZE);
if (batch.length > 0) {
lastId = batch[batch.length - 1]._id;
}
batchCount = batch.length;
2021-03-11 10:41:35 +01:00
const entriesToProcess = batch.filter(shouldBeProcessed(processedLocaleCodes));
2021-03-02 17:09:35 +01:00
2021-03-11 10:41:35 +01:00
const updatesInfo = getUpdatesInfo({ entriesToProcess, attributesToMigrate });
2021-03-02 17:09:35 +01:00
const updates = updatesInfo.map(({ entriesIdsToUpdate, attributesValues }) => ({
updateMany: { filter: { _id: { $in: entriesIdsToUpdate } }, update: attributesValues },
}));
await model.bulkWrite(updates);
}
processedLocaleCodes.push(locale.code);
}
};
module.exports = migrateForMongoose;