-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathupdateAssetURLForGQL.ts
More file actions
72 lines (64 loc) · 2.21 KB
/
updateAssetURLForGQL.ts
File metadata and controls
72 lines (64 loc) · 2.21 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
/**
* Updates asset URLs in a GraphQL response in-place. Walks the response data,
* finds RTE fields that have `embedded_itemsConnection`, and sets each
* embedded asset's `asset-link` attribute in the JSON to the asset's `url`
* from the response. Use after fetching content via GraphQL so RTE JSON
* contains correct asset URLs for rendering.
*
* @param gqlResponse - The raw GraphQL response object (e.g. `{ data: { ... } }`). Modified in place.
*/
export function updateAssetURLForGQL(gqlResponse:any) {
try {
const response = gqlResponse?.data;
for (let contentType in response) {
if ("items" in response[contentType]) {
const entries = response[contentType].items;
entries.forEach((entry:any) => { // iterate over all entries
processEntry(entry);
});
} else {
processEntry(response[contentType]);
}
}
} catch (error) {
console.error('Error in updating asset URL for GQL response', error);
}
}
function processEntry(entry:any) {
for (let field in entry) {
const fieldData = entry[field];
if (fieldData instanceof Array) {
fieldData.forEach((data:any) => {
findRTEFieldAndUpdateURL(data);
});
} else if (fieldData && typeof fieldData === 'object') {
findRTEFieldAndUpdateURL(fieldData);
}
}
}
function findRTEFieldAndUpdateURL(fieldData:any) {
const rteField = findRTEField(fieldData);
if (!rteField) return;
const edges = rteField?.embedded_itemsConnection?.edges;
edges.forEach((edge:any) => {
const node = edge.node;
if (node?.url && node?.filename) {
if (!node?.system?.uid) throw new Error('Asset UID not found in the response');
const correspondingAsset = rteField?.json?.children?.find((child:any) => child.attrs['asset-uid'] === node.system.uid);
correspondingAsset.attrs['asset-link'] = node.url;
}
});
}
function findRTEField(fieldData: any): any {
if (fieldData && fieldData.embedded_itemsConnection) {
return fieldData;
}
for (const key in fieldData) {
if (fieldData[key] && typeof fieldData[key] === 'object') {
const found = findRTEField(fieldData[key]);
if (found) {
return found;
}
}
}
}