Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 62 additions & 45 deletions server/src/functions/should-set-downloaded-property.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,68 +36,85 @@ export enum ShouldSetDownloadedPropertyReturnType {
JSON = 'json',
}

export const shouldSetDownloadedProperty = (
/**
* Locate the field a downloaded key belongs to, using the Content Transfer Setup.
*
* - `YES`: the key is a plain field enabled for transfer (the field is the key's last segment).
* - `JSON`: the key is one leaf of an enabled `json` or `blocks` field, which the upload flattens
* into one key per leaf; `fieldSegmentIndex` is the index in `parsedKeyRest` of the segment
* naming that field. Everything before it is the path to the entry or component owning the
* field (dynamic zone `id;component` segments and component ids included); everything after it
* is the leaf's path inside the field's value, e.g. for
* `beats[3;about.timeline].stops[10].notes[0].children[0].text` the field is `notes` (index 4)
* of stop 10 of timeline 3, and for `tags[0]` or `years.2024` it is `tags` / `years` (index 0).
* - `NO`: anything else (field disabled or unknown, component gone, model not set up).
*/
export const locateDownloadedField = (
modelContentTransferSetup: ModelContentTransferSetup,
parsedKeyRest: string[]
): ShouldSetDownloadedPropertyReturnType => {
): { type: ShouldSetDownloadedPropertyReturnType; fieldSegmentIndex: number } => {
const notFound = { type: ShouldSetDownloadedPropertyReturnType.NO, fieldSegmentIndex: -1 };
if (!modelContentTransferSetup.__model__) {
return ShouldSetDownloadedPropertyReturnType.NO;
return notFound;
}

if (hasDynamicZoneKeySegment(parsedKeyRest)) {
const dynamicZonePropertyName = getDynamicZonePropertyName(parsedKeyRest);
const componentName = getComponentNameFromDynamicZoneKeySegment(getDynamicZoneKeySegment(parsedKeyRest));
let setupModel: unknown = modelContentTransferSetup;
let startIndex = 0;

if (hasDynamicZoneKeySegment(parsedKeyRest)) {
const dynamicZoneKeySegmentIndex = getDynamicZoneKeySegmentIndex(parsedKeyRest);
const componentName = getComponentNameFromDynamicZoneKeySegment(parsedKeyRest[dynamicZoneKeySegmentIndex]);
const dzContentTransferSetupModel = get(
modelContentTransferSetup,
dynamicZonePropertyName
getDynamicZonePropertyName(parsedKeyRest)
) as ModelContentTransferSetupDZFields[];
if (!Array.isArray(dzContentTransferSetupModel)) {
return ShouldSetDownloadedPropertyReturnType.NO;
return notFound;
}

const dzContentTransferSetupComponentModel = dzContentTransferSetupModel.find(
(c) => c.__component__ === componentName
);

if (!dzContentTransferSetupComponentModel) {
return ShouldSetDownloadedPropertyReturnType.NO;
setupModel = dzContentTransferSetupModel.find((c) => c.__component__ === componentName);
if (!setupModel) {
return notFound;
}
startIndex = dynamicZoneKeySegmentIndex + 1;
}

const dynamicZoneKeySegmentIndex = getDynamicZoneKeySegmentIndex(parsedKeyRest);
const slicedParsedKeyRest = parsedKeyRest.slice(dynamicZoneKeySegmentIndex + 1);
const filteredSlicedParsedKeyRest = slicedParsedKeyRest.filter((segment) => isNaN(parseInt(segment)));

if (get(dzContentTransferSetupComponentModel, filteredSlicedParsedKeyRest) === true) {
return ShouldSetDownloadedPropertyReturnType.YES;
// positions of the named (non-numeric) segments; numeric ones are array positions or component ids
const namedSegmentIndexes: number[] = [];
for (let index = startIndex; index < parsedKeyRest.length; index++) {
if (isNaN(parseInt(parsedKeyRest[index]))) {
namedSegmentIndexes.push(index);
}
}

// json fields
while (filteredSlicedParsedKeyRest.length > 0) {
// last segment out
filteredSlicedParsedKeyRest.pop();
if (get(dzContentTransferSetupComponentModel, filteredSlicedParsedKeyRest) === true) {
return ShouldSetDownloadedPropertyReturnType.JSON;
}
// the longest named path enabled in the setup is the field
for (let length = namedSegmentIndexes.length; length > 0; length--) {
const fieldPath = namedSegmentIndexes.slice(0, length).map((index) => parsedKeyRest[index]);
if (get(setupModel, fieldPath) === true) {
const fieldSegmentIndex = namedSegmentIndexes[length - 1];
// anything after the field's own segment is a path inside a json/blocks value
const type =
fieldSegmentIndex === parsedKeyRest.length - 1
? ShouldSetDownloadedPropertyReturnType.YES
: ShouldSetDownloadedPropertyReturnType.JSON;
return { type, fieldSegmentIndex };
}
}

return ShouldSetDownloadedPropertyReturnType.NO;
} else {
const filteredParsedKeyRest = parsedKeyRest.filter((partialKey) => isNaN(parseInt(partialKey)));

if (get(modelContentTransferSetup, filteredParsedKeyRest) === true) {
return ShouldSetDownloadedPropertyReturnType.YES;
}
return notFound;
};

// json fields
while (filteredParsedKeyRest.length > 0) {
// last segment out
filteredParsedKeyRest.pop();
if (get(modelContentTransferSetup, filteredParsedKeyRest) === true) {
return ShouldSetDownloadedPropertyReturnType.JSON;
}
}
export const shouldSetDownloadedProperty = (
modelContentTransferSetup: ModelContentTransferSetup,
parsedKeyRest: string[]
): ShouldSetDownloadedPropertyReturnType => {
return locateDownloadedField(modelContentTransferSetup, parsedKeyRest).type;
};

return ShouldSetDownloadedPropertyReturnType.NO;
}
/** Index of the `json`/`blocks` field's own segment in `parsedKeyRest`, or -1 (see `locateDownloadedField`). */
export const getJsonFieldSegmentIndex = (
modelContentTransferSetup: ModelContentTransferSetup,
parsedKeyRest: string[]
): number => {
const { type, fieldSegmentIndex } = locateDownloadedField(modelContentTransferSetup, parsedKeyRest);
return type === ShouldSetDownloadedPropertyReturnType.JSON ? fieldSegmentIndex : -1;
};
119 changes: 13 additions & 106 deletions server/src/services/localazy-transfer-download-service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { findSetupModelByCollectionUid } from '../utils/transfer-setup-utils';
import config from '../config';
import { isoLocalazyToStrapi } from '../utils/iso-locales-utils';
import {
shouldSetDownloadedProperty,
ShouldSetDownloadedPropertyReturnType,
} from '../functions/should-set-downloaded-property';
import { set, get, isEmpty } from 'lodash-es';
import { collectDownloadedContent, DownloadedLocalazyKey } from '../utils/collect-downloaded-content';
import { isEmpty } from 'lodash-es';
import RequestInitiatorHelper from '../utils/request-initiator-helper';
import PluginSettingsServiceHelper from '../services/helpers/plugin-settings-service-helper';
import { EventType } from '../constants/events';
Expand All @@ -22,7 +18,7 @@ import {
getEntryExclusionService,
getActivityLogsService,
} from '../core';
import { Language, Locales } from '@localazy/api-client';
import { Locales } from '@localazy/api-client';
import { SyncCursor } from '../db/model/sync-cursor';
import { JobNotificationServiceType } from './helpers/job-notification-service';

Expand Down Expand Up @@ -282,15 +278,9 @@ const LocalazyTransferDownloadService = ({ strapi }: { strapi: Core.Strapi }) =>
/**
* Parse Localazy content
*/
type ParsedLocalazyContent = Record<Language['code'], Record<UID.ContentType, Record<string, any>>>;

const parsedLocalazyContent: ParsedLocalazyContent = {};
const strapiContentTypesModels = await StrapiService.getModels();
const jsonFields = [];

// Track which Localazy keys contribute to each Strapi entry: "isoStrapi:uid:documentId" → [{lang, id, event}]
const entryKeySourceMap: Record<string, Array<{ lang: string; id: string; event: number | undefined }>> = {};

const languagesToParse: Array<{ isoStrapi: string; keys: DownloadedLocalazyKey[] }> = [];
for (const [isoLocalazy, keys] of Object.entries<any>(localazyContent)) {
const isoStrapi = isoLocalazyToStrapi(isoLocalazy);
if (!isoStrapi) {
Expand All @@ -299,100 +289,17 @@ const LocalazyTransferDownloadService = ({ strapi }: { strapi: Core.Strapi }) =>
});
continue;
}

for (const localazyEntry of keys) {
const key = localazyEntry.key[0];
const value = localazyEntry.value;
const localazyKeyId: string = localazyEntry.id;
const localazyKeyEvent: number | undefined = localazyEntry.event;

// Skip keys already processed at the same or newer event for this language
const storedEvent = processedKeys[isoStrapi]?.[localazyKeyId];
if (storedEvent !== undefined && localazyKeyEvent !== undefined && localazyKeyEvent <= storedEvent) {
continue;
}

const parsedKey = StrapiI18nService.parseLocalazyKey(key);

// Track source key for this entry
const entryKey = `${isoStrapi}:${parsedKey.uid}:${parsedKey.id}`;
if (!entryKeySourceMap[entryKey]) {
entryKeySourceMap[entryKey] = [];
}
entryKeySourceMap[entryKey].push({ lang: isoStrapi, id: localazyKeyId, event: localazyKeyEvent });

const modelContentTransferSetup = findSetupModelByCollectionUid(
contentTransferSetup,
strapiContentTypesModels,
parsedKey.uid
);

if (typeof modelContentTransferSetup !== 'undefined') {
const shouldSetDownloadedPropertyResult = shouldSetDownloadedProperty(
modelContentTransferSetup,
parsedKey.rest
);
if (shouldSetDownloadedPropertyResult === ShouldSetDownloadedPropertyReturnType.NO) {
continue;
}

let parsedKeyRestWithoutComponents = parsedKey.rest;
if (shouldSetDownloadedPropertyResult === ShouldSetDownloadedPropertyReturnType.JSON) {
const setKey = [isoStrapi, parsedKey.uid, parsedKey.id];

// handle dynamic zones and components here
let updatedParsedKeyRestWithoutComponents = parsedKeyRestWithoutComponents;
let segmentsToAdd = [];
for (const segment of parsedKeyRestWithoutComponents) {
const hasEntry = get(modelContentTransferSetup, [...segmentsToAdd, segment]);
const hasEntryNotFinal = hasEntry && typeof hasEntry !== 'boolean';
// const isDZ = Array.isArray(hasEntry) && hasEntry.every((entry) => entry.__component__);
// processed till here in iterations and `segment` is numeric
const isComponent = parseInt(segment) > 0;

if (hasEntryNotFinal || (!hasEntry && isComponent)) {
segmentsToAdd.push(segment);
setKey.push(segment);
updatedParsedKeyRestWithoutComponents = updatedParsedKeyRestWithoutComponents.slice(1);
} else {
break;
}
}
parsedKeyRestWithoutComponents = updatedParsedKeyRestWithoutComponents;

let foundJsonFieldIndex = jsonFields.findIndex((jsonField) => {
return jsonField.setKey.join() === setKey.join();
});
if (foundJsonFieldIndex === -1) {
jsonFields.push({
setKey,
jsonKey: parsedKeyRestWithoutComponents[0],
jsonValue: {},
});
}

foundJsonFieldIndex = foundJsonFieldIndex === -1 ? jsonFields.length - 1 : foundJsonFieldIndex;
const foundJsonField = jsonFields[foundJsonFieldIndex];
// rest from index 1
const restSliced = parsedKeyRestWithoutComponents.slice(1);
set(foundJsonField, ['jsonValue', ...restSliced], value);
jsonFields[foundJsonFieldIndex] = foundJsonField;
}

if (shouldSetDownloadedPropertyResult === ShouldSetDownloadedPropertyReturnType.YES) {
const setKey = [isoStrapi, parsedKey.uid, parsedKey.id, ...parsedKeyRestWithoutComponents];
set(parsedLocalazyContent, setKey, value);
}
}
}
languagesToParse.push({ isoStrapi, keys });
}

/**
* Set json fields if applicable
*/
for (const jsonField of jsonFields) {
set(parsedLocalazyContent, [...jsonField.setKey, jsonField.jsonKey], jsonField.jsonValue);
}
// Track which Localazy keys contribute to each Strapi entry: "isoStrapi:uid:documentId" → [{lang, id, event}]
const { parsedLocalazyContent, entryKeySourceMap } = collectDownloadedContent({
languages: languagesToParse,
processedKeys,
contentTransferSetup,
models: strapiContentTypesModels,
parseLocalazyKey: (key) => StrapiI18nService.parseLocalazyKey(key),
});

/**
* Iterate over parsed Localazy content and insert/update content in Strapi
Expand Down
10 changes: 2 additions & 8 deletions server/src/services/strapi-i18n-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Core, UID, Modules } from '@strapi/strapi';
import { intlDisplayName } from '../utils/intl-display-name';
import { isoLocalazyToStrapi } from '../utils/iso-locales-utils.js';
import { omitDeep } from '../utils/omit-deep.js';
import { parseLocalazyKey } from '../utils/parse-localazy-key';
// import { getStrapiService } from '../core';
import type { Locale } from '../models/strapi/locale';
// TODO: ADD TYPES
Expand Down Expand Up @@ -36,14 +37,7 @@ const StrapiI18nService = ({ strapi }: { strapi: Core.Strapi }) => ({
}
},
parseLocalazyKey(key: string) {
const split = key.split(/\.(?![^[]*])|\[|\]/);
const filteredSplit = split.filter((item) => item !== '');

return {
uid: `${filteredSplit[0]}.${filteredSplit[1]}`,
id: filteredSplit[2],
rest: filteredSplit.slice(3),
};
return parseLocalazyKey(key);
},

async getEntryInLocale(
Expand Down
23 changes: 2 additions & 21 deletions server/src/services/strapi-localazy-i18n-service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { parsedLocalazyEntryToCreateEntry } from '../utils/parsed-localazy-entry-to-create-entry';
import { buildLocalizedCreateEntry } from '../utils/build-localized-create-entry';
import { parsedLocalazyEntryToUpdateEntry } from '../utils/parsed-localazy-entry-to-update-entry';
import { omitDeep } from '../utils/omit-deep';
import { merge } from 'lodash-es';
import { Core, UID } from '@strapi/strapi';
import { dropDocumentIdExceptMedia } from '../utils/drop-property-deep';
import { getStrapiI18nService /*, getStrapiService*/ } from '../core';
// TODO: ADD TYPES

Expand All @@ -15,30 +12,14 @@ const StrapiLocalazyI18nService = ({ strapi }: { strapi: Core.Strapi }) => ({
// Strapi i18n Service
const StrapiI18nService = getStrapiI18nService();

const { createEntry } = parsedLocalazyEntryToCreateEntry(
const mergedCreateEntry = buildLocalizedCreateEntry(
strapiContentTypesModels,
translatedModel,
baseEntry,
uid,
isoStrapi
);

const omitKeys = ['locale', 'localizations', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy', 'publishedAt'];

let filteredBaseEntry = omitDeep(baseEntry, omitKeys);
// TODO: Deal with relations - must be omitted
// Drop documentId from all objects except media objects (images, files, etc.)
filteredBaseEntry = dropDocumentIdExceptMedia(filteredBaseEntry);

/**
* Items positioning is done by the `toCreateEntry` function
* that's why can entry can be merged now
*/
let mergedCreateEntry: Record<string, any> = {};
merge(mergedCreateEntry, filteredBaseEntry, createEntry);
mergedCreateEntry = omitDeep(mergedCreateEntry, omitKeys);

mergedCreateEntry.locale = isoStrapi;
const createdEntry = await StrapiI18nService.createLocalizationForAnExistingEntry(
uid,
baseEntry,
Expand Down
Loading
Loading