-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathextractEntries.ts
More file actions
126 lines (108 loc) · 4.33 KB
/
extractEntries.ts
File metadata and controls
126 lines (108 loc) · 4.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import fs from 'fs';
import path from 'path';
import config from '../config/index.json';
const { contentTypes: contentTypesConfig } = config?.modules;
const contentTypeFolderPath = path.resolve(config?.data, contentTypesConfig?.dirName);
const EXCLUDED_POST_TYPES = new Set(['attachment', 'wp_global_styles', 'wp_navigation']);
const normalizeArray = <T>(value: T | T[] | undefined): T[] => {
if (!value) return [];
return Array.isArray(value) ? value : [value];
};
const idCorrector = (id: string) => {
const normalized = id?.replace(/[-{}]/g, '');
return normalized ? normalized.toLowerCase() : id;
};
const getEntryName = (item: any): string => {
if (typeof item?.title === 'string' && item.title.trim()) {
return item.title.trim();
}
if (item?.title?.text) {
return String(item.title.text).trim();
}
if (typeof item?.['wp:post_name'] === 'string' && item['wp:post_name'].trim()) {
return item['wp:post_name'].trim();
}
return 'Untitled Entry';
};
/**
* Must match api WordPress entry keys: idCorrector(`posts_${wp:post_id}`) in wordpress.service.ts.
* Raw post id only caused otherCmsEntryUid to diverge from uid-map / entry JSON keys → entry mapper showed "-".
*/
const getSourceEntryUid = (item: any): string => {
const postId = item?.['wp:post_id'];
if (postId != null && String(postId).trim() !== '') {
return idCorrector(`posts_${postId}`);
}
const candidate =
item?.guid?.text ?? item?.guid ?? item?.link ?? getEntryName(item);
return idCorrector(String(candidate || ''));
};
const getEntryLanguage = (item: any, channelLanguage?: string): string => {
const postMeta = normalizeArray(item?.['wp:postmeta']);
const languageMeta = postMeta.find((meta: any) => {
const key = String(meta?.['wp:meta_key'] || '').toLowerCase();
return key === 'language' || key === '_language' || key === 'locale' || key === '_locale';
});
const metaLanguage = languageMeta?.['wp:meta_value'];
if (typeof metaLanguage === 'string' && metaLanguage.trim()) {
return metaLanguage.trim();
}
if (typeof channelLanguage === 'string' && channelLanguage.trim()) {
return channelLanguage.trim();
}
return 'en-us';
};
const extractEntries = async (filePath: string, contentTypeData: any[] = []) => {
try {
const rawData = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(rawData);
const items = normalizeArray(jsonData?.rss?.channel?.item);
const channelLanguage = jsonData?.rss?.channel?.language;
const groupedByType = items?.reduce((acc: Record<string, any[]>, item: any) => {
const postType = item?.['wp:post_type'] || 'unknown';
if (EXCLUDED_POST_TYPES.has(postType)) return acc;
if (!acc[postType]) acc[postType] = [];
acc[postType].push(item);
return acc;
}, {});
const updatedTypes = contentTypeData?.map((ct) => ({ ...ct }));
for (const [type, entries] of Object.entries(groupedByType)) {
const entryMapping = normalizeArray(entries)
.map((item: any) => {
const otherCmsEntryUid = getSourceEntryUid(item);
if (!otherCmsEntryUid) return null;
return {
contentTypeUid: type,
entryName: getEntryName(item),
otherCmsEntryUid: `posts_${otherCmsEntryUid}`,
otherCmsCTName: type,
language: getEntryLanguage(item, channelLanguage),
isUpdate: false
};
})
.filter(Boolean);
const contentTypeFilePath = path.join(contentTypeFolderPath, `${type.toLowerCase()}.json`);
if (fs.existsSync(contentTypeFilePath)) {
const ctFile = JSON.parse(await fs.promises.readFile(contentTypeFilePath, 'utf8'));
ctFile.entryMapping = entryMapping;
await fs.promises.writeFile(contentTypeFilePath, JSON.stringify(ctFile, null, 4), 'utf8');
}
const index = updatedTypes.findIndex(
(ct: any) =>
ct?.otherCmsUid?.toLowerCase?.() === type.toLowerCase() ||
ct?.contentstackUid?.toLowerCase?.() === type.toLowerCase()
);
if (index >= 0) {
updatedTypes[index] = {
...updatedTypes[index],
entryMapping
};
}
}
return updatedTypes;
} catch (error: any) {
console.error('Error while extracting WordPress entries:', error?.message || error);
return contentTypeData;
}
};
export default extractEntries;