Skip to content

Commit 35fea9d

Browse files
Merge pull request #811 from contentstack/fix/CMG-721
refactor: improve file writing logic in aem.service.ts, attaching ref…
2 parents 55c64b8 + 13b4c1e commit 35fea9d

File tree

4 files changed

+57
-45
lines changed

4 files changed

+57
-45
lines changed

api/src/services/aem.service.ts

Lines changed: 53 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,12 @@ function findAssetByPath(
105105
}
106106

107107
async function writeOneFile(indexPath: string, fileMeta: any) {
108-
fs.writeFile(indexPath, JSON.stringify(fileMeta), (err) => {
109-
if (err) {
110-
console.error('Error writing file: 3', err);
111-
}
112-
});
108+
try {
109+
await fs.promises.writeFile(indexPath, JSON.stringify(fileMeta));
110+
} catch (err) {
111+
console.error('Error writing file:', err);
112+
throw err;
113+
}
113114
}
114115

115116
async function writeFiles(
@@ -121,23 +122,18 @@ async function writeFiles(
121122
try {
122123
const indexPath = path.join(entryPath, 'index.json');
123124
const localePath = path.join(entryPath, `${locale}.json`);
124-
fs.access(entryPath, async (err) => {
125-
if (err) {
126-
fs.mkdir(entryPath, { recursive: true }, async (err) => {
127-
if (err) {
128-
console.error('Error writing file: 2', err);
129-
} else {
130-
await writeOneFile(indexPath, fileMeta);
131-
await writeOneFile(localePath, entryLocale);
132-
}
133-
});
134-
} else {
135-
await writeOneFile(indexPath, fileMeta);
136-
await writeOneFile(localePath, entryLocale);
137-
}
138-
});
139-
} catch (error) {
125+
126+
try {
127+
await fs.promises.access(entryPath);
128+
} catch {
129+
await fs.promises.mkdir(entryPath, { recursive: true });
130+
}
131+
132+
await fs.promises.writeFile(indexPath, JSON.stringify(fileMeta));
133+
await fs.promises.writeFile(localePath, JSON.stringify(entryLocale));
134+
} catch (error) {
140135
console.error('Error writing files:', error);
136+
throw error;
141137
}
142138
}
143139

@@ -484,19 +480,27 @@ function processFieldsRecursive(fields: any[], items: any, title: string, assetJ
484480
break;
485481
}
486482
case 'reference': {
487-
for (const [, val] of Object.entries(items) as [string, Record<string, unknown>][]) {
483+
const fieldKey = getLastKey(field?.contentstackFieldUid);
484+
const refCtUid = field?.referenceTo?.[0] || field?.uid;
485+
486+
for (const [key, val] of Object.entries(items) as [string, Record<string, unknown>][]) {
487+
if (!val?.configured || (val[':type'] as string) === 'nt:folder') {
488+
continue;
489+
}
490+
488491
if (
489-
(typeof field?.uid === 'string' && !['title', 'url'].includes(field.uid)) &&
490-
field?.contentstackFieldType === "reference" &&
491-
(val[':type'] as string) !== 'nt:folder' &&
492-
val?.configured
492+
(val[':type'] as string)?.includes('experiencefragment') &&
493+
typeof val?.localizedFragmentVariationPath === 'string'
493494
) {
494-
if (typeof val?.localizedFragmentVariationPath === 'string' &&
495-
val.localizedFragmentVariationPath.includes(`/${field?.uid}`)) {
496-
obj[field?.uid as string] = [{
495+
const pathMatchesField = val.localizedFragmentVariationPath.includes(`/${field?.uid}`);
496+
const pathMatchesRefType = val.localizedFragmentVariationPath.includes(`/${refCtUid}`);
497+
498+
if (pathMatchesField || pathMatchesRefType) {
499+
obj[fieldKey] = [{
497500
"uid": val?.id,
498-
"_content_type_uid": field?.uid,
501+
"_content_type_uid": refCtUid
499502
}];
503+
break;
500504
}
501505
}
502506
}
@@ -559,7 +563,6 @@ const createEntry = async ({
559563
contentTypes,
560564
destinationStackId,
561565
projectId,
562-
// keyMapper,
563566
project
564567
}: CreateEntryOptions) => {
565568
const srcFunc = 'createEntry';
@@ -569,17 +572,21 @@ const createEntry = async ({
569572
const assetJson = path.join(assetsSave, ASSETS_SCHEMA_FILE);
570573
const exists = await isAssetJsonCreated(assetJson);
571574
let assetJsonData: Record<string, AssetJSON> = {};
575+
572576
if (exists) {
573577
const assetData = await fs.promises.readFile(assetJson, 'utf-8');
574578
if (typeof assetData === 'string') {
575579
assetJsonData = JSON.parse(assetData);
576580
}
577581
}
582+
578583
const entriesDir = path.resolve(packagePath ?? '');
579584
const damPath = path.join(entriesDir, AEM_DAM_DIR);
580585
const entriesData: Record<string, Record<string, any[]>> = {};
581586
const allLocales: object = { ...project?.master_locale, ...project?.locales };
582587
const entryMapping: Record<string, string[]> = {};
588+
589+
// FIRST PASS: Process all entries and build mappings
583590
for await (const fileName of read(entriesDir)) {
584591
const filePath = path.join(entriesDir, fileName);
585592
if (filePath?.startsWith?.(damPath)) {
@@ -599,11 +606,11 @@ const createEntry = async ({
599606
const data = containerCreator(contentType?.fieldMapping, items, title, assetJsonData);
600607
data.uid = uid;
601608
data.publish_details = [];
609+
602610
if (contentType?.contentstackUid && data && mappedLocale) {
603611
const message = getLogMessage(
604612
srcFunc,
605-
`Entry title "${data?.title}"(${contentType?.contentstackUid}
606-
}) in the ${mappedLocale} locale has been successfully transformed.`,
613+
`Entry title "${data?.title}"(${contentType?.contentstackUid}) in the ${mappedLocale} locale has been successfully transformed.`,
607614
{}
608615
);
609616
await customLogger(
@@ -625,25 +632,30 @@ const createEntry = async ({
625632
for (const entry of entries) {
626633
const flatData = deepFlattenObject(entry);
627634
for (const [key, value] of Object.entries(flatData)) {
628-
if (key.endsWith('._content_type_uid')) {
629-
const uidFeild = key.replace('._content_type_uid', '');
630-
if (uidFeild && typeof value === 'string') {
631-
const refs: string[] = entryMapping?.[value];
632-
if (refs?.length) {
633-
_.set(entry, `${uidFeild}.uid`, refs?.[0]);
634-
}
635+
if (key.endsWith('._content_type_uid') && typeof value === 'string') {
636+
const uidField = key.replace('._content_type_uid', '');
637+
const refs: string[] = entryMapping?.[value];
638+
639+
if (refs?.length) {
640+
_.set(entry, `${uidField}.uid`, refs[0]);
641+
} else {
642+
console.info(`✗ No entry found for content type: ${value}`);
635643
}
636644
}
637645
}
638646
}
647+
const entriesObject: Record<string, any> = {};
648+
for (const entry of entries) {
649+
entriesObject[entry.uid] = entry;
650+
}
639651
const fileMeta = { '1': `${locale}.json` };
640652
const entryPath = path.join(
641653
process.cwd(),
642654
entrySave,
643655
ctUid,
644656
locale
645657
);
646-
await writeFiles(entryPath, fileMeta, entries, locale);
658+
await writeFiles(entryPath, fileMeta, entriesObject, locale);
647659
}
648660
}
649661
}

ui/src/components/AdvancePropertise/index.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ const AdvancePropertise = (props: SchemaProps) => {
6767
value: item
6868
}));
6969

70-
const referencedItems = props?.data?.referenceTo?.map((item: string) => ({
70+
const referencedItems = props?.data?.refrenceTo?.map((item: string) => ({
7171
label: item,
7272
value: item
7373
}));

ui/src/components/ContentMapper/contentMapper.interface.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export interface FieldMapType {
6767
contentstackUid: string;
6868
_invalid?: boolean;
6969
backupFieldUid: string;
70-
referenceTo: string[];
70+
refrenceTo: string[];
7171
}
7272

7373
export interface Advanced {

ui/src/components/ContentMapper/index.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ const ContentMapper = forwardRef(({ handleStepChange }: contentMapperProps, ref:
333333
// Make title and url field non editable
334334
useEffect(() => {
335335
tableData?.forEach((field) => {
336-
if(field?.backupFieldType === 'reference' && field?.referenceTo?.length === 0) {
336+
if(field?.backupFieldType === 'reference' && field?.refrenceTo?.length === 0) {
337337
field._canSelect = false;
338338
}
339339
else if (field?.backupFieldType !== 'text' && field?.backupFieldType !== 'url') {
@@ -860,7 +860,7 @@ const ContentMapper = forwardRef(({ handleStepChange }: contentMapperProps, ref:
860860
if (row?.uid === rowId && row?.contentstackFieldUid === rowContentstackFieldUid) {
861861
const updatedRow = {
862862
...row,
863-
referenceTo: updatedSettings?.referenedItems,
863+
refrenceTo: updatedSettings?.referenedItems,
864864
advanced: { ...row?.advanced, ...updatedSettings }
865865
};
866866
return updatedRow;

0 commit comments

Comments
 (0)