Back

This article provides example code for data transformation functions and event and visitor functions.

The Data Transformation Functions feature is currently in early access and only open to select customers at this time.  For more information, see (TBD - link to early access announcement).

In this article:

Data Transformation Function Examples

Delete a Variable

In this example, the function deletes a variable containing sensitive data (email address).

transform((event) => {
    delete event.data.udo.user.email;
});

Populate a Variable

The following example populates the page_name variable with the title.

transform((event) => {
    if (!event.data.udo.page_name) {
        event.data.udo.page_name = event.data.dom.title;
    }
});

Create a Variable

This example create a page_hierarchy variable from multiple variables.

transform((event) => {
    const { site_region, site_section, category_name } = event.data.udo;
    event.data.udo.page_hierarchy = '${site_region}:${site_section}:${category_name}';
});

The following example creates site_section, site_category, and site_subcategoryvariables based on the pathname.

transform((event) => {
    const [,site_section, site_category, site_subcategory] = event.data.dom.pathname.split("/");
    Object.assign(event.data.udo, {
        site_section,
        site_category,
        site_subcategory
    })
});

Map a Value to a Variable

The following example maps a value to category_name based on the value of category_id :

const categoryNameById = {
    38: "Mobile",
    39: "Engagement",
    40: "Monitoring"
};

transform((event) => {
    event.data.udo.products = event.data.udo.products
        .map(product => ({
            ...product,
            category_name: categoryNameById[product.category_id]
        }));
});

Modify an Existing Variable

The following example changes a variable to all lowercase.

transform((event) => {
    const searchKeyword = event.data.udo.search_keyword;
    if (searchKeyword) {
        event.data.udo.search_keyword = searchKeyword.toLowerCase();
    }
});

This example renames a variable by setting its value to a new variable and deleting the existing variable.

transform((event) => {
    event.data.udo.page_title = event.data.udo.page_name;
    delete event.data.udo.page_name;
});

Concatenate Values and Create a New Variable

This example concatentates two values and deletes one of the values. It also creates a new variable.

import flatten from 'tealium/util/flatten';

// "transform" function allows you to access event and apply changes
transform((event) => {
    // concatenate test1 and test2 properties
    const { test1, test2 } = event.data.udo;
    event.data.udo.test_concatenated = `${test1}:${test2}`;
    
    // delete test1 property
    delete event.data.udo.test1;
    
    // add a new test3 property
    event.data.udo.test3 = 'TEST3';

    console.log(JSON.stringify(event, null, 2));
})

Event and Visitor Function Examples

Sending Event Data with HTTP POST

The following example shows how to make an HTTP POST request to an endpoint with event data in the request body JSON.

// Send event data - HTTP POST
import {event} from 'tealium';

console.log(JSON.stringify(event));

fetch('https://webhook.site/87bb160f-475a-4258-b117-693bb2378a4d',
    {
        method: 'POST',
        body: JSON.stringify(event),
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok. Status code: ${response.status}.');
        }
        return response.json();
    })
    .then(data => console.log('Response:', JSON.stringify(data)))
    .catch(error => console.log('Error:', error.message));

Sending Event Data with HTTP GET

The following example shows how to make an HTTP GET request to an endpoint with event data as query string parameters.

// Send event data - HTTP GET
import {event} from 'tealium';

console.log(JSON.stringify(event));

fetch(encodeURI('https://webhook.site/87bb160f-475a-4258-b117-693bb2378a4d?param=${event.data}'))
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok. Status code: ${response.status}.');
        }
        return response.json();
    })
    .then(data => console.log('Response:', JSON.stringify(data)))
    .catch(error => console.log('Error:', error.message));

Sending Visitor Data with HTTP POST

The following example shows how to make an HTTP POST request to an endpoint with visitor profile data in the request body JSON.

// Send visitor data - HTTP POST
import {visitor} from 'tealium';

console.log(JSON.stringify(visitor));
fetch('https://webhook.site/87bb160f-475a-4258-b117-693bb2378a4d',
    {
        method: 'POST',
        body: JSON.stringify(visitor), 
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok. Status code: ${response.status}.');
        }
        return response.json();
    })
    .then(data => console.log('Response:', JSON.stringify(data)))
    .catch(error => console.log('Error:', error.message));

Sending Visitor Data with HTTP GET

The following example shows how to make an HTTP GET request to an endpoint with visitor profile data as query string parameters.

// Send visitor data - HTTP GET
import {visitor} from 'tealium';

console.log(JSON.stringify(visitor));

fetch(encodeURI('https://webhook.site/87bb160f-475a-4258-b117-693bb2378a4d?param=${visitor.data}'))
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok. Status code: ${response.status}.');
        }
        return response.json();
    })
    .then(data => console.log('Response:', JSON.stringify(data)))
    .catch(error => console.log('Error:', error.message));

Querying Visitor Data and Sending It to the Tealium Collect HTTP API

The following example shows how to make an HTTP GET request to retrieve weather data, then send that data to the Tealium Collect HTTP API. In this example, the function uses the IP address to get the location city, gets weather information for that city, and sends the city and weather information to the Tealium Collect HTTP API.

import { auth, visitor, event } from "tealium";

console.log(JSON.stringify(visitor));

const ip_stack_api_key = 'your_api_key',
      weather_api_key = 'your_weather_api_key',
      ip_address = visitor?.current_visit?.properties?.ip_address;

console.log(ip_address);
(async function() {
    if(ip_address) {
    try {
        // Use IP address to get location city
        let city_response = await fetch('https://api.ipstack.com/${ip_address}?access_key=${ip_stack_api_key}&format=1'),
        city_data = await city_response.json();
        console.log(JSON.stringify(city_data));
        // Use location city to get local weather
        let weather_response = await fetch(encodeURI('https://api.openweathermap.org/data/2.5/weather?q=${city_data.city}&appid=${weather_api_key}')),
            weather_data = await weather_response.json();
            console.log(JSON.stringify(weather_data));
        // Send city and weather description back into collect endpoint
        await fetch(encodeURI('https://collect.tealiumiq.com/event?tealium_account=cloud-functions-usecases&tealium_profile=main&tealium_visitor_id=${visitor._id}&lookup_city=${weather_data?.name}&weather=${weather_data?.weather?.[0]?.description}&country=isp=${city_data?.connection?.isp}'));
    } catch(e) {
        console.error(e);
        return false;
    }
    } else {
        console.error("Could not locate users IP address")
    }
})();

Getting a Facebook Authentication Token

The following code example shows how to get a Facebook authentication token:

import { auth } from 'tealium';
const token = auth.get('facebook_token');

fetch('https://graph.facebook.com/v8.0/act_12345678/customaudiences??access_token=${token}&fields=approximate_count%2Csubtype%2Cname%2Cdata_source&limit=10')
  .then(response => response.json())
  .then(data => console.log('Data:', data))
  .catch(error => console.log('Error:', error.message));

Sending Data to Facebook

The following example shows how to send event data to the Facebook Graph or Marketing API to create a campaign (https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group).

import {auth, event} from 'tealium';

const ACT_ID = 11111111111;
const ACCESS_TOKEN = auth.get("facebook_token");

fetch('https://graph.facebook.com/v8.0/act_${ACT_ID}/campaigns?access_token=${ACCESS_TOKEN}',
    {
        method: 'POST',
        body: 'name=${event.data}&objective=PAGE_LIKES&status=PAUSED&special_ad_categories=[]'
    })
    .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok. Status code: ${response.status}.');
            }
            return response.json();
        })
    .then(data => console.log('Response:', JSON.stringify(data)))
    .catch(error => console.log('Error:', error.message));

Multiple HTTP Requests and Different EndPoints

The following example shows making an HTTP request, and then, depending on the response, make another HTTP request to a separate endpoint.

import { auth } from "tealium";

const ACT_ID = 11111111111;
const ACCESS_TOKEN = auth.get("facebook_token");

(async function () {
    console.time('function');
    try {
        console.log('Creating campaign...');
        let campaignId = await createCampaign({ campaignName: 'My Campaign' });
        console.log('Campaign ID', campaignId);

        console.log('Creating custom audience...');
        let customAudienceId = await createCustomAudience({ caName: 'My_Audience' });
        console.log('Custom Audience ID', customAudienceId);

        console.log('Creating ad set...');
        customAudienceId = 23846304008770411;
        let adSetId = await createAdSet({ campaignId: campaignId, customAudienceId: customAudienceId });
        console.log('Ad Set ID', adSetId);

        console.log('Creating ad creative...');
        // let adCreativeId = await createAdCreative();
        // current API call not working, use an ID created manually before
        let adCreativeId = 'adCreativeId';
        console.log('AdCreative ID ', adCreativeId);

        console.log('Creating ad...');
        let adId = await createAd({ adsetId: adSetId, adCreativeId: adCreativeId });
        console.log('Ad ID', adId);
        console.timeEnd('function');
    } catch (error) {
        console.log(error);
    }
})();

async function createAd({ adsetId, adCreativeId }) {
    const params = {
        'status': 'PAUSED',
        'adset_id': adsetId,
        'name': 'My Ad',
        'creative': { 'creative_id': adCreativeId },
    };

    let result = await fetch('https://graph.facebook.com/v7.0/act_${ACT_ID}/ads?access_token=${ACCESS_TOKEN}',
        {
            method: 'POST',
            body: jsonToRequestBodyString(params)
        });
    let json = await result.json();
    return json.id;
}

async function createAdSet({ campaignId, customAudienceId }) {
    const params = {
        'name': 'AdSet',
        'lifetime_budget': '1000',
        'start_time': '2020-07-01T23:41:41-0800',
        'end_time': '2020-07-07T23:41:41-0800',
        'campaign_id': campaignId,
        'bid_amount': '1',
        'billing_event': 'IMPRESSIONS',
        'optimization_goal': 'LINK_CLICKS',
        'targeting': {
            "geo_locations": {
                "countries": ["US"],
            },
            "age_min": 25,
            "age_max": 40,
            "custom_audiences": [{ "id": customAudienceId }]
        },
        'status': 'PAUSED'
    };
    let result = await fetch('https://graph.facebook.com/v7.0/act_${ACT_ID}/adsets?access_token=${ACCESS_TOKEN}',
        {
            method: 'POST',
            body: jsonToRequestBodyString(params)
        });
    let json = await result.json();
    return json.id;
}

async function createCustomAudience({ caName }) {
    const params = {
        'name': caName,
        'subtype': 'CUSTOM',
        'description': 'People who purchased on my website',
        'customer_file_source': 'USER_PROVIDED_ONLY',
    };
    let result = await fetch('https://graph.facebook.com/v7.0/act_${ACT_ID}/customaudiences?access_token=${ACCESS_TOKEN}',
        {
            method: 'POST',
            body: jsonToRequestBodyString(params)
        });
    let json = await result.json();
    return json.id;
}

async function createCampaign({ campaignName }) {
    const params = {
        'objective': 'LINK_CLICKS',
        'status': 'PAUSED',
        'buying_type': 'AUCTION',
        'name': campaignName,
        'special_ad_categories': 'NONE'
    };
    let result = await fetch('https://graph.facebook.com/v8.0/act_${ACT_ID}/campaigns?access_token=${ACCESS_TOKEN}',
        {
            method: 'POST',
            body: jsonToRequestBodyString(params)
        });
    let json = await result.json();
    return json.id;
}

function jsonToRequestBodyString(json) {
    return Object.keys(json).map(function (key) {
        return encodeURIComponent(key) + '=' +
            ((typeof json[key] === 'string' || json[key] instanceof String) ? encodeURIComponent(json[key]) : JSON.stringify(json[key]));
    }).join('&');
}

Additional Information

Public