Skip to main content

[Workflow Builder - GCW] Using the JavaScript Activity with V2 Engine

Juliana Maciel Maruri da Cunha avatar
Written by Juliana Maciel Maruri da Cunha
Updated yesterday

This article provides a comprehensive guide on utilizing the JavaScript activity within Workflow Builder. It covers the core concepts, available functions, how to access and modify workflow context, and best practices for writing effective JavaScript code. By the end of this article, you will have a clear understanding of how to leverage JavaScript to enhance your workflows.


Understanding the JavaScript Activity

The JavaScript activity in Workflow Builder allows you to execute custom JavaScript code directly within your workflows. This feature enables advanced data manipulation, conditional logic setup, and integration with other systems, depending on your workflow's configuration. The JavaScript code runs in a secure environment powered by Goja, which is a pure Go implementation of ECMAScript 5.1, ensuring stability and security.


Available Functions and Objects

In the JavaScript activity, you have access to a limited set of built-in JavaScript objects and a custom log function for logging messages. The available objects include:

  • Math: Provides mathematical functions and constants (e.g., Math.random(), Math.floor()).

  • JSON: Methods for parsing and stringifying JSON data (e.g., JSON.parse(), JSON.stringify()).

  • Date: Functions for handling dates and times (e.g., new Date(), Date.now()).

  • Array: The global Array object for array manipulation.

  • String: The global String object for text manipulation.

  • Number: The global Number object for numerical operations.

  • Boolean: The global Boolean object for true/false values.

  • Error: The global Error object for error handling.

  • log: A custom function to output messages to the activity's logs.

Example of using the log function:

JavaScript
log("This message will appear in the activity logs.");
log("The value of a variable is: " + someVariable);

Accessing Workflow Context

Your JavaScript code can access the entire workflow context through a global variable named context. This object contains the current state and data of your workflow, allowing you to read and modify values as permitted by your workflow's configuration.

Here’s an example of a typical context structure:

JSON
{
"flow:batch:0": {
"batchUid": "692576827",
"batchedBy": {
"CoatingType": "glossy-lamination",
"ColorType": "4-4"
},
"quantity": "1"
},
"payload": {
"facility": {
"countryId": "DE",
"name": "DE_GCSB",
"timeZone": "Europe/Berlin"
},
"files": {
"default": "https://..."
},
"order": {
"amount": "19.99",
"clientId": "test-orders",
"deliveryAddress": {
"address_line_1": "123 Test St",
"city": "Testville",
// ... more address details
},
// ... more order details
},
"part": {
"id": "7101535136",
"productDetails": {
"attributes": {
"CoatingType": "glossy-lamination",
"ColorType": "4-4",
// ... more attributes
},
"derivedAttributes": {
"height": {
"value": "55"
},
// ... more derived attributes
}
}
}
// ... more payload data
},
"step:print:0": {
"machine": {
"0": "digital-presses-hp-indigo-7900",
"#": "1"
},
"machineTypes": "digital-presses",
"sheetSizes": {
"0": "sra3",
"#": "1"
}
}
}

The context object is rich with data, including payload, flow:batch:0, and step:print:0.

Examples of accessing values from the context:

JavaScript
// Get the client ID from the order payload
var clientId = context.payload.order.clientId;
log("Client ID: " + clientId);

// Access a product attribute
var coatingType = context.payload.part.productDetails.attributes.CoatingType;
log("Product Coating Type: " + coatingType);

// Access a derived attribute's value
var productHeight = context.payload.part.productDetails.derivedAttributes.height.value;
log("Product Height: " + productHeight);

// Get the customer's city from the delivery address
var city = context.payload.order.deliveryAddress.city;
log("Delivery City: " + city);

// You can also modify context values (if allowed by workflow permissions)
context.payload.order.deliveryAddress.city = "New Testville";
log("Updated Delivery City: " + context.payload.order.deliveryAddress.city);

Important Note: The structure of the context object varies based on your specific workflow. Always refer to your workflow's input and previous activity outputs for accurate data paths.


Writing Your JavaScript Code

Your JavaScript code will be automatically wrapped in an immediately invoked function expression (IIFE) for safe execution. You do not need to include this wrapper in your code; simply write the JavaScript statements you wish to execute.


Returning Results

The JavaScript activity can return values that will be stored in the activity's output. The format of the returned value depends on its type:

  • Returning a JavaScript object: The properties will be mapped as key-value pairs in the JSCodeOutput.

  • Returning other values: Values like strings, numbers, booleans, or arrays will be wrapped under a default key called "result" in the JSCodeOutput.

Example: Returning an object

JavaScript
var myResult = {
status: "success",
message: "Order processed",
orderId: context.payload.order.id
};
return myResult;

This will produce an output similar to:

JSON
{
"flow:js-script:1": {
"message": "Order processed",
"orderId": "048aa79f-7d6e-45bd-930a-81be07be0f19",
"status": "success"
},
"payload": {...}
}

Example: Returning a non-object value (string)

JavaScript
return "Processing complete for order " + context.payload.order.customerOrderId;

This will result in an output like:

JSON
{
"result": "Processing complete for order test-order-ref"
}

Example: Returning an array

JavaScript
var attributes = context.payload.part.productDetails.attributes;
var attributeNames = Object.keys(attributes);
return attributeNames;

This will result in an output like:

JSON
{
"result": ["CoatingType", "ColorType", "Orientation", "PaperFormat", "PaperType", "ProductStatus", "ProtectionType", "ShapeEdgeType", "SpotFinishingType", "State", "Variable"]
}

Debugging and Logging

The log() function is essential for debugging within the JavaScript activity. Any messages sent to log() will be displayed in the Logs section of the activity's output, allowing you to track execution flow and inspect variable values.


Best Practices

  • Keep it focused: Use the JavaScript activity for specific data transformations or conditional checks. More complex logic is better handled by dedicated workflow steps or external services.

  • Use try...catch: Wrap your code in try...catch blocks to handle unexpected errors gracefully and prevent workflow failures.

  • Validate inputs: Always check that the data from the context exists and is in the expected format before using it.

  • Test thoroughly: Rigorously test your JavaScript code with various inputs to ensure correct behavior under different scenarios.

By adhering to these guidelines, you can effectively utilize the JavaScript activity to introduce powerful custom logic and flexibility into your Workflow Builder workflows.


📝 Not what you needed?

Help us improve this article, send us an email to [email protected] — please include the article title.

Did this answer your question?