Script Include For a Rest Instruction inside a Business Rule

Sidhartha Bose
Tera Contributor

This is my business rule

(function executeRule(current, previous /*, g*/) {
// Get the category value from the current record
var categoryValue = current.getValue('category');

// Instantiate the FetchingSolutions script include
var fetchingSolutions = new FetchingSolutions();

// Set the URL and authentication credentials for the REST request
var apiUrl = 'https://dev.anakage.com/api/teams/category?facility=demo';
var username = 'demo_admin';
var password = 'Test#123';

// Invoke the script include method to make the REST request
var data = fetchingSolutions.getRequestWithAuth(apiUrl, username, password);

// Add a delay of 5 seconds (5000 milliseconds)
setTimeout(function() {
// Continue with the script after the delay

// Create an instance of the SolutionLinkGenerator script include
var solutionLinkGenerator = new SolutionLinkGenerator();

// Process categories and generate a single string with messages using the script include
var resultString = solutionLinkGenerator.processCategories(data, categoryValue);

// Display an info message on the form with the generated resultString
gs.addInfoMessage(resultString);

// Update the record
current.x_1061975_anakag_0_test24 = resultString;
current.update();

// Uncomment the line below if you want to cancel the save operation when the annotation is empty
// current.setAbortAction(true);
}, 5000); // 5000 milliseconds (5 seconds) delay

})(current, previous);

 

THESE are the script includes

 

(function executeRule(current, previous /*, g*/) {
// Get the category value from the current record
var categoryValue = current.getValue('category');

// Instantiate the FetchingSolutions script include
var fetchingSolutions = new FetchingSolutions();

// Set the URL and authentication credentials for the REST request
var apiUrl = 'https://dev.anakage.com/api/teams/category?facility=demo';
var username = 'demo_admin';
var password = 'Test#123';

// Invoke the script include method to make the REST request
var data = fetchingSolutions.getRequestWithAuth(apiUrl, username, password);

// Add a delay of 5 seconds (5000 milliseconds)
setTimeout(function() {
// Continue with the script after the delay

// Create an instance of the SolutionLinkGenerator script include
var solutionLinkGenerator = new SolutionLinkGenerator();

// Process categories and generate a single string with messages using the script include
var resultString = solutionLinkGenerator.processCategories(data, categoryValue);

// Display an info message on the form with the generated resultString
gs.addInfoMessage(resultString);

// Update the record
current.x_1061975_anakag_0_test24 = resultString;
current.update();

// Uncomment the line below if you want to cancel the save operation when the annotation is empty
// current.setAbortAction(true);
}, 5000); // 5000 milliseconds (5 seconds) delay

})(current, previous);

 

 

var SolutionLinkGenerator = Class.create();
SolutionLinkGenerator.prototype = {
initialize: function() {},

generateSolutionLinks: function(category, selectedCategoryValue) {
if (category.category !== selectedCategoryValue) {
return ''; // Skip if the category doesn't match the selected value
}

var solutionLinks = [];

for (var i = 0; i < category.solutions.length; i++) {
var solution = category.solutions[i];
var url = 'https://dev.anakage.com/api/solutions/download?sn=' + solution.sol_num;
var link = '<a href="' + url + '" target="_blank">' + solution.sol_name + '</a>';
solutionLinks.push(link);
}

return 'Available Solutions in Selected Category: ' + category.category + '<br>' + solutionLinks.join('<br>') + '<br><br>';
},

processCategories: function(data, selectedCategoryValue) {
var resultString = '';

for (var j = 0; j < data.length; j++) {
var category = data[j];
var solutionLinks = this.generateSolutionLinks(category, selectedCategoryValue);

resultString += solutionLinks;
}

return resultString;
},

type: 'SolutionLinkGenerator'
};

 

 

 

IF i replace the var data in the business rule so that i feed it the responsebody as a static data this code runs and i get my desired output . The moment i try to run it dynamically using fetchingsolutions script include as a GET request and put its data in the variable this code no longer works and i dont get my desired output can somebody please tell me the problem here and how to fix it.

4 REPLIES 4

AnveshKumar M
Tera Sage
Tera Sage

@Sidhartha Bose Can you provide the fetching solutions script include? It seems you pasted the BR two times.

Thanks,
Anvesh

Sidhartha Bose
Tera Contributor

Sorry I included the Business Rule twice this is the script include for fetching solutions

var FetchingSolutions = Class.create();

FetchingSolutions.prototype = {
initialize: function() {},

// Function to make a REST API GET request with basic authentication
getRequestWithAuth: function(url, username, password) {
var request = new sn_ws.RESTMessageV2();
request.setEndpoint(url);
request.setHttpMethod("GET");

// Set Basic Authentication credentials
request.setBasicAuth('demo_admin', 'Test#123');

var response = request.execute();
var responseBody = response.getBody();

return responseBody;
},

type: 'FetchingSolutions'
};

Hi @Sidhartha Bose 

Try the following in your script include method.

 

var FetchingSolutions = Class.create();

 

FetchingSolutions.prototype = {

initialize: function() {},

 

// Function to make a REST API GET request with basic authentication

getRequestWithAuth: function(url, username, password) {

try{

var sm = new sn_ws.RESTMessageV2();

sm.setEndpoint(url);

sm.setHttpMethod("GET");

 

// Set Basic Authentication credentials

sm.setBasicAuth('demo_admin', 'Test#123');

var requestBody;

var responseBody;

var status;

var sm;

 response = sm.execute();//Might throw exception if http connection timed out or some issue with sending request itself because of encryption/decryption of password.

 responseBody = response.haveError() ? response.getErrorMessage() : response.getBody();

 status = response.getStatusCode();

} catch(ex) {

 responseBody = ex.getMessage();

 status = '500';

} finally {

 requestBody = sm ? sm.getRequestBody():null;

}

gs.info("Request Body: " + requestBody);

gs.info("Response: " + responseBody);

gs.info("HTTP Status: " + status);

 

return responseBody;

},

 

type: 'FetchingSolutions'

};

 

 

And observe the logs, if it didn't work.

 

Please mark my answer helpful and accept as a solution if it helped 👍

Thanks,
Anvesh

Aniket Chavan
Tera Sage
Tera Sage

Hello @Sidhartha Bose ,

Please give a try to the modified script below and let me know how it works for you.

Business Rule:

(function executeRule(current, previous /*, g*/) {
    // Get the category value from the current record
    var categoryValue = current.getValue('category');

    // Instantiate the FetchingSolutions script include
    var fetchingSolutions = new FetchingSolutions();

    // Set the URL and authentication credentials for the REST request
    var apiUrl = 'https://dev.anakage.com/api/teams/category?facility=demo';
    var username = 'demo_admin';
    var password = 'Test#123';

    // Use a callback to handle the asynchronous REST request
    fetchingSolutions.getRequestWithAuth(apiUrl, username, password, function(data) {
        // Create an instance of the SolutionLinkGenerator script include
        var solutionLinkGenerator = new SolutionLinkGenerator();

        // Process categories and generate a single string with messages using the script include
        var resultString = solutionLinkGenerator.processCategories(data, categoryValue);

        // Display an info message on the form with the generated resultString
        gs.addInfoMessage(resultString);

        // Update the record
        current.x_1061975_anakag_0_test24 = resultString;
        current.update();

        // Uncomment the line below if you want to cancel the save operation when the annotation is empty
        // current.setAbortAction(true);
    });

})(current, previous);

 

Script Include:

var FetchingSolutions = Class.create();
FetchingSolutions.prototype = {
    initialize: function() {},

    getRequestWithAuth: function(apiUrl, username, password, callback) {
        // Make your AJAX request here
        // Example using jQuery:
        jQuery.ajax({
            url: apiUrl,
            type: 'GET',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ':' + password));
            },
            success: function (data) {
                // Call the callback function with the retrieved data
                callback(data);
            },
            error: function (error) {
                // Handle error if needed
                console.error(error);
            }
        });
    },

    type: 'FetchingSolutions'
};

 

Let me know your views on this and Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks,
Aniket