Creating CodeFusion Script

The Add script page in CodeFusion provides a simple interface for creating and customizing data processing scripts. Use these scripts to integrate APIs, perform on-the-fly data transformation, and prepare dynamic inputs for your Active Content blocks.

To create a CodeFusion script:

  1. On the CodeFusion page, select + Add script file. The Add script window is displayed.
  2. Enter a Script Name.

    This name becomes the identifier for your function in the script editor. Choose a clear, business-relevant name (for example, getUserProfile). The "_main" suffix is automatically appended for execution purposes in the script area, but you only need to specify the base name (such as getUserProfile). The full function will appear as getUserProfile_main in the editor.

  3. Provide a Description to document the script's purpose.

  4. Click Save. Your new script now appears in the CodeFusion script list.

  5. Click your script name to open the editor.

  6. Enter your JavaScript function.

    Note: All parameters you define in your main function will become input parameters for this API in Active Content.

  7. Click Save to store your work.

  8. Click Publish to make the script available for integration.

Example: Fetching a User Profile

This example demonstrates a typical retail use case—fetching a customer profile by user ID from an external API. It includes error handling and logs for easier troubleshooting.

Copy
// Fetches a user's profile by userId from an external API and returns the profile data.
function getUserProfile_main(userId) {
  var output = {};

  // Construct the API URL with the provided userId
  var apiUrl = "https://api.example.com/users/" + encodeURIComponent(userId);

  try {
    // Make a GET request to the user profile API
    var response = api.get(apiUrl)
      .putHeader("Accept", "application/json") // Ask for JSON response
      .withReqTimeOut(2)                      // Set timeout to 2 seconds
      .enableCache(30)                     // Cache the response for 30 minutes
      .invokeForJson();                       // Parse the response as JSON

    // Use the JSON data from the API response if available
    output = response.json || {};
  } catch (error) {
    // Log the error for debugging in the console    
    console.log("[getUserProfile_main] API call failed:"+ error);

    // Return a simple fallback user profile
    output = {
      userId: userId,
      name: "Unknown User",
      status: "unavailable"
    };
  }

  // Log the output for testing/debugging
    console.log("[getUserProfile_main] Output:"+ output);

  // Return the user profile data
  return output;
}

What this example shows:

  • Input parameters are mapped directly to the function signature and become API inputs in Active Content.

  • The script constructs a URL using the input, makes a GET request, and safely parses the response.

  • Errors are handled gracefully, providing a fallback profile object.