zuora to eloqua | Cell 29 | Cell 31 | Search

This code is a JavaScript program that performs conditional logic, retrieves configuration and token data from a JSON file, and makes API calls to Eloqua using OAuth authentication. The program handles both successful and error scenarios, logging responses or sending errors to the client as needed.

Cell 30


if(typeof $ !== 'undefined') {
    $.async();
    var eloquaToken, eloquaConfig = JSON.parse(fs.readFileSync(PROFILE_PATH + '/.credentials/eloqua_production.json').toString().trim());
    eloquaOauth(eloquaConfig)
        .then(r => {
            eloquaToken = r;
            return getEloquaExistingImport("eloquaToken",
"eloquaConfig")
        })
        /*
        .then(r => {
            // delete import definitions
            const imports = JSON.parse(r.body).items;
            return importer.runAllPromises(imports.map(r => resolve => {
                return request({
                    followAllRedirects: true,
                    uri: eloquaConfig.rest_api_url + '/bulk/2.0' + r.uri,
                    method: 'DELETE',
                    headers: {
                        'Authorization': "Bearer " + eloquaToken.access_token,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                }).then(r => resolve(r)).catch(e => resolve(e))
            }))
        })
        */
        .then(r => {
            console.log(r);
            $.mime({'text/html': '<pre>' + JSON.stringify(r, null, 4) + '</pre>'});
        })
        .catch(e => $.sendError(e))
}

// TODO: find other definitions, compare, and import using the same definition

What the code could have been:

const fs = require('fs');
const axios = require('axios');

// Load Eloqua configuration from file
consteloquaConfig = JSON.parse(fs.readFileSync(PROFILE_PATH + '/.credentials/eloqua_production.json', 'utf8'));

// Function to obtain Eloqua token using OAuth
async function obtainEloquaToken(config) {
    try {
        const response = await axios.post(`${config.rest_api_url}/oauth2/token`, null, {
            headers: {
                'Authorization': 'Basic'+ Buffer.from(`${config.client_id}:${config.client_secret}`).toString('base64'),
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            params: {
                'grant_type': 'client_credentials'
            }
        });
        return response.data.access_token;
    } catch (error) {
        throw new Error(`Failed to obtain Eloqua token: ${error.message}`);
    }
}

// Function to get Eloqua existing imports
async function getEloquaExistingImports(token, config) {
    try {
        const response = await axios.get(`${config.rest_api_url}/bulk/2.0/import/definitions`, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        });
        return response.data;
    } catch (error) {
        throw new Error(`Failed to retrieve Eloqua existing imports: ${error.message}`);
    }
}

// Main execution
if (typeof $!== 'undefined') {
    $.async();
    const eloquaToken = await obtainEloquaToken(eloquaConfig);
    try {
        const existingImports = await getEloquaExistingImports(eloquaToken, eloquaConfig);
        console.log(existingImports);
        $.mime({ 'text/html': '<pre>' + JSON.stringify(existingImports, null, 4) + '</pre>' });
    } catch (error) {
        $.sendError(error);
    }
} else {
    throw new Error('$ is undefined');
}

// TODO: find other definitions, compare, and import using the same definition
// This can be achieved by implementing a function that takes two lists of existing imports as input,
// compares them, and returns the differences.

Code Breakdown

Conditional Block

if (typeof $!== 'undefined') {
    //...
}

Token and Configuration Retrieval

var eloquaToken, eloquaConfig = JSON.parse(fs.readFileSync(PROFILE_PATH + '/.credentials/eloqua_production.json').toString().trim());

OAuth and API Call

eloquaOauth(eloquaConfig)
   .then(r => {
        eloquaToken = r;
        return getEloquaExistingImport(eloquaToken, eloquaConfig)
    })

API Call ( commented out )

/*
.then(r => {
    // delete import definitions
    const imports = JSON.parse(r.body).items;
    return importer.runAllPromises(imports.map(r => resolve => {
        return request({
            //...
        }).then(r => resolve(r)).catch(e => resolve(e))
    }))
})
*/

Success and Error Handling

.then(r => {
    console.log(r);
    $.mime({'text/html': '<pre>' + JSON.stringify(r, null, 4) + '</pre>'});
})
.catch(e => $.sendError(e))