Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save robisatthefunction/b1cbc503bb5544750c08433a714b69a4 to your computer and use it in GitHub Desktop.
Save robisatthefunction/b1cbc503bb5544750c08433a714b69a4 to your computer and use it in GitHub Desktop.
// Learn more about destination functions API at
// https://segment.com/docs/connections/destinations/destination-functions
/**
* Handle track event
* @param {SegmentTrackEvent} event
* @param {FunctionSettings} settings
*/
// Learn more about destination functions API at
// https://segment.com/docs/connections/destinations/destination-functions
/**
* Handle track event
* @param {SegmentTrackEvent} event
* @param {FunctionSettings} settings
*/
async function onTrack(event, settings) {
// Learn more at https://segment.com/docs/connections/spec/track/
/* This code uses Optimizely's Event API to forward Segment Events to Optimizely */
// https://docs.developers.optimizely.com/experimentation-data/docs/send-using-event-api
// This is generating a random Id for each individual event, which is required by the Optimizely Event API. It is different from the visitor ID and event ID.
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (c) {
var r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
}
);
}
// This concatenates the event name and event properties so that the it makes a more descriptive event name for Optimizely
let eventName = event.event + event.properties.section;
// This is getting optimizely's user identifier called the optimizelyEndUserId. You can set this ID as a property in your events by getting it from the optimizelyEndUserId cookie or window.optimizely.get('visitor').visitorId
// https://support.optimizely.com/hc/en-us/articles/4410284260365-Cookies-and-localStorage-in-snippets#01H8BSGB9BCHMENQZGH6S65CA7
let visitor_id = event.properties.optimizelyEndUserId;
// get revenue and value from Segment
let revenue = event.properties.revenue;
let value = event.properties.value;
// Optimizely's Event API requires the entity ID of the event you are sending. This code is getting the entity ID of the event that the function is currently trying to send
// https://docs.developers.optimizely.com/web-experimentation/docs/locate-ids-used-for-apis#campaign-id-experiment-id-variation-ids-entity-ids-and-keys
let entity_id;
switch (eventName) {
case 'Example API Name 1':
entity_id = '1234456678';
break;
case 'Example API Name 2':
entity_id = '2345678899';
default:
entity_id = null;
}
// Endpoint and payload for the Optimizely conversion event POST request
const endpoint = 'https://logx.optimizely.com/v1/events';
let body = {
account_id: '<account_id>', // Replace with your Optimizely account ID
visitors: [
{
visitor_id: visitor_id,
attributes: [],
snapshots: [
{
decisions: [],
events: [
{
entity_id: entity_id,
key: eventName,
timestamp: Date.now(),
uuid: uuidv4(), // need to add function to generate uuid
type: "other",
tags: {
revenue: 12345.678,
value: "134.55",
quantity: "990.8"
},
properties: {
color: "blue",
numeric_property: "1234"
}
}
]
}
]
}
],
anonymize_ip: true,
client_name: 'Optimizely/event-api-demo',
client_version: '1.0.0',
enrich_decisions: true
};
let response;
try {
response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
});
} catch (error) {
// Retry on connection error
throw new RetryError(error.message);
}
if (response.status >= 500 || response.status === 429) {
// Retry on 5xx (server errors) and 429s (rate limits)
throw new RetryError(`Failed with ${response.status}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment