Example code

This article provides code examples for data transformation functions.

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));
})

Get 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 Facebook HTTP requests

The following example shows multiple HTTP requests to Facebook to create an audience, a campaign, and an ad.

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('&');
}

Was this page helpful?

This page was last updated: January 7, 2023