-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.js
More file actions
76 lines (71 loc) · 2.3 KB
/
template.js
File metadata and controls
76 lines (71 loc) · 2.3 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
/*
* A template for Braze-Cloudinary integration that allows marketers to use
* a given asset from a campaign, based on Braze liquid tags and Cloudinary metadata
*
* Read https://cloudinary.com/documentation/custom_functions#javascript_filters for
* overview and for instructions how to deploy
*
*
* *Adopting the below template*
* Skip the "Helper functions" section and
* Edit the "Main" section with your use case fields, values, and logic
*
*
* *URL structure to be put in Braze*
* https://<Base_URL>/<resource_type>/list/$locale_!en!/$audience_!Internal!/fn_select:js:v<js_epoch_seconds>:template.js/v<url_epoch_seconds>/<campaign_tag>.json
* See https://github.com/cloudinary-devs/braze-personalization/blob/main/README.md for more details.
*/
/* Helper functions */
function getTxParts(tx) {
const txParts = {};
tx.split("/").forEach(el => el.split(',').forEach(el2 => {
const parts = el2.split('_', 2);
if (parts[0] && parts[1]) {
txParts[parts[0]] = parts[1]
}
}));
return txParts;
}
function getParam(txParts, arg) {
return txParts["$" + arg]?.split('!')[1];
}
function getMetadataDict(metadata) {
return metadata.reduce((acc, el) => {
acc[el.external_id] = el;
return acc;
}, {});
}
function haveMetadata(md, arg, value) {
return md[arg]?.value === value || md[arg]?.value[value];
}
function fallbackImage(publicId, tx) {
return { public_id: publicId,
transformation: tx.substring(0, tx.lastIndexOf("/")),
};
}
/* End helper functions */
/* Main */
function main() {
// Boilerplate code
const content = JSON.parse(getDocument());
const tx = getContext()["transformation"];
const txParts = getTxParts(tx);
// Input parameters
const locale = getParam(txParts, "locale");
const audience = getParam(txParts, "audience");
// Main logic
for (const resource of content) {
if (!resource.metadata) continue;
try {
const md = getMetadataDict(resource.metadata);
if (
haveMetadata(md, "audience", audience) &&
haveMetadata(md, "locale", locale)
) {
return resource;
}
} catch (e) {}
}
// Default if no matches found (fallback)
return fallbackImage("samples/two-ladies", tx);
}