JavaScript Editor

Customer JS editor in Nected is a way to define any complex, specific business need which is not possible via a no-code editor. One can write complex logical conditions, set up any complex output to the rule as well as can do any data manipulation, or transformation along with fetching data from external data sources via API.

It’s all tokenized to use any of your custom inputs, dataset, or output data to build any kind of conditions, or result or create additional data post-rule execution wherein you want to manipulate or transform the result.

Its design and functionality are tailored to meet the diverse needs of Nected's user base, ranging from products to developers to data analysts.

Access Javascript Editor:

Now, using the Javascript Editor inside a rule and a workflow is pretty simple. The Formula editor is available inside:

  1. Rule:

    1. Rule Conditions

    2. Rule Result

  2. Workflow:

    1. Code Node

    2. In SetVariable node

    3. Response node

JS in Conditions

  1. Simplified Formulas for Conditions:

    Users can craft straightforward formulas that evaluate to a boolean value. These formulas are useful for making quick decisions based on certain criteria.

    {{.customInput.orderAmount}} > 5000 && {{.dataSet.isPriorityCustomer}}

    This formula evaluates whether an order amount exceeds 5000 and if the customer is categorized as a priority, thereby returning a true or false value based on these conditions.

  2. Building Complex Conditions:

    For more intricate scenarios, users can construct complex conditions using if-else statements. These conditions allow for detailed decision-making processes in the application.

    function processData() {
        // Calculate discount based on order quantity and customer type
        var orderQuantity = {{.customInput.orderQuantity}};
        var customerType = {{.dataSet.customerType}};
        var discount = 0;
    
        if (orderQuantity > 50 && customerType === 'wholesale') {
            discount = 0.1; // 10% discount for bulk orders from wholesale customers
        }
    
        var finalDiscount = orderQuantity * discount;
        finalDiscount; // This is the implicit return value
    }
    
    // Call the function and store the returned value
    var discountValue = processData();

    In this example, the code checks if an order qualifies for a bulk discount based on order quantity and customer type, then returns a boolean indicating the discount's applicability.

Return Types in Conditions

For conditions, it's essential that the final expression evaluates to either true or false. The editor enforces this requirement by blocking any non-boolean expressions to maintain clear and predictable logic flow within the application.

JS in Results

  1. Mathematical Formulas for Deriving Values:

    For straightforward calculations, such as financial computations, users can implement formulas directly.

    {{.customInput.loanAmount}} * ({{.customInput.annualInterest}} / (12 * 100)) * (Math.pow(1 + ({{.customInput.annualInterest}} / (12 * 100)), {{.customInput.loanTenure}}) / (Math.pow(1 + ({{.customInput.annualInterest}} / (12 * 100)), {{.customInput.loanTenure}}) - 1))
  2. Transforming/Manipulating Data:

    More sophisticated data manipulation requires full JS code to parse, transform, or combine data points.

    // Example: Transform user data for display
    let userData = {{.customInput.userInfo}};
    let displayName = userData.firstName + ' ' + userData.lastName.toUpperCase();
    let displayData = {
      name: displayName,
      memberSince: new Date(userData.membershipStart).getFullYear()
    };
    displayData;
  3. JS in Additional Data:

    JS can also be used in the context of additional data, specifically for decision table rules in Nected. This usage allows for dynamic data manipulation based on the rule's logic.

    {{.customInput.salesFigure}} * {{.globalVar.commissionRate}}

These examples demonstrate the versatility of the custom editor, which enables users to construct complex logical conditions, perform a wide array of calculations, and manipulate data in ways that suit their specific application requirements. By integrating JavaScript directly within the editor, Nected empowers users to build custom, sophisticated solutions tailored to their operational needs.

Return Types in Results

The return types in results are crucial for the appropriate functioning of the application. The custom editor in Nected expects specific types of values to be returned based on the context.

  • In most cases, the result should be a numerical value or a transformed data object.

  • Currently, returning null or undefined is not accepted, but upcoming updates to the editor will introduce more flexibility by allowing null returns with warnings, while still blocking undefined returns.

Best Practices for Return Types

To maintain consistency and reliability in code execution within Nected, users should follow these best practices:

  • For Conditions: Always ensure that conditions evaluate to boolean values. Use explicit comparison operations or boolean expressions that inherently result in true or false.

  • For Results: Although upcoming updates will provide more leniency for null returns, it’s still a best practice to return meaningful values from functions and operations. If a function might return null, consider using default values or error handling to provide an alternative result.

By adhering to these guidelines regarding expected return types, users can create more robust and error-resistant applications within Nected. This careful attention to the nature of return values contributes significantly to the overall stability and reliability of the platform’s applications.

JS Code editor For Workflow:

The JavaScript (JS) code editor embedded within a workflow environment serves as a versatile tool for enhancing functionality and customization. It enables developers to write custom scripts that define and manipulate variables, generate dynamic responses, and execute complex computations.

Usecase of JS Code in Workflow:

Real-Time Data Manipulations

JS facilitates real-time data manipulations within workflows. By processing data dynamically, workflows can optimize resource allocations and strategic decisions in response to immediate data updates, enhancing operational efficiency and flexibility.

This Example show the eligibility of loan based on certain criteria

function evaluateLoanEligibility() {
    // Retrieve attributes from the predefined tokens
    var age = {{.Trigger.age}};
    var existingLoans = {{.NewDemoDB_.output[0].existing_loans}};
    var loanAmount = 	

    // Perform some calculations
    var eligibilityScore = (age * loanAmount) / (existingLoans + 1);

    // Example condition based on attributes and calculations
    var isEligible = (age >= 18 && loanAmount > 0 && existingLoans < 5 && eligibilityScore > 1000);

    // Return the boolean eligibility result
    return isEligible;
}

// Call the function to evaluate loan eligibility and return the result
evaluateLoanEligibility();

The Js editor in workflow can be seen in Three Nodes:

  1. Set Variable Node

  2. Response Node

  3. Code Node

Js Code Editor in Set Variable Node:

The JavaScript code editor within the Set Variable node is a fundamental tool in workflow design, enabling the setting or updating of variable values through custom scripts. These variables, computed dynamically using JavaScript, can then be utilized by other nodes for advanced data manipulation, enhancing the flexibility and functionality of the workflow.

Steps to Access and Use the JS Code Editor for Custom Logic In Set Variable Node

  1. Adding the Set Variable Node:

    • Select the workflow.

    • Click on the + icon to add a new node.

    • Select the Set Variable node from the list of available nodes.

  2. Accessing the JavaScript Code Editor:

    • After choosing the node, select the input param tab and click on the + Add field button. A dropdown will appear; select JS CODE from the dropdown.

    • Click on JS Code, and the JS code editor will open. Use the editor to define the logic for setting the variable.

  3. Custom Function Scripting:

  4. Testing and Debugging:

    • Test and debug your script using the Test Button. The editor provides real-time error detection, flagging any syntax errors.

    • Ensure your script is error-free and save the changes by clicking on the Save Button.

  5. Integration of Final Result:

    • Place the result output variable at the end of your script to finalize your custom logic for decision-making in the system.

JavaScript Code Editor in Response Node:

The JavaScript code editor within the Response node is a powerful tool in workflow design, enabling the transmission of dynamically computed data back to the caller. This ensures seamless communication between workflows and their callers, enhancing the flexibility and functionality of the workflow.

Steps to Access and Use the JS Code Editor for Custom Logic In Set Variable Node

  1. Adding the Set Variable Node:

    • Select the workflow.

    • Click on the + icon to add a new node in the workflow.

    • Select the Set Variable node from the list of available nodes.

  2. Accessing the JavaScript Code Editor:

    • After choosing the node, select the input param tab and click on the + Add field button. A dropdown will appear; select JS CODE from the dropdown.

    • Click on JS Code, and the JS code editor will open. Use the editor to define the logic for setting the Response Node.

  3. Custom Function Scripting:

  4. Testing and Debugging:

    • Test and debug your script using the Test Button. The editor provides real-time error detection, flagging any syntax errors.

    • Ensure your script is error-free and save the changes by clicking on the Save Button.

  5. Integration of Final Result:

    • Place the result output variable at the end of your script to finalize your custom logic for decision-making in the system.

JavaScript Code Editor in Custom Code Node:

The Custom Code Node allows users to execute custom JavaScript code within the workflow. This provides flexibility to perform complex computations, data manipulations, or integrate custom logic.

  1. Adding the Custom Code Node:

    • Click on the + icon to add a new node.

    • Select the Custom Code node from the list of available nodes and place it on the workflow canvas.

  2. Configuration Tabs for Custom Code Node:

    • After Choosing the node select input param tab, click on Select Language Drop down.

    • After click that you will see two options which are Javascript and Formula. choose javascript for js code editor

    • After selecting it the javascript language the editor which is already present will be shifted to Js code environment

  3. Custom Function Scripting:

  4. Testing and Debugging:

    • Test and debug your script using the Test Button. The editor provides real-time error detection, flagging any syntax errors.

    • Ensure your script is error-free and save the changes by clicking on the Save Button.

  5. Integration of Final Result:

    • Place the result output variable at the end of your script to finalize your custom logic for decision-making in the system.

Pre-configured Tokens in Different Contexts

In Nected's custom editor, the availability of pre-configured tokens varies depending on the context in which JavaScript is being used. These tokens are crucial for referencing dynamic content within your code, whether in conditions, results, or additional data. Below is a breakdown of the types of tokens accessible in each context:

  1. Tokens in Conditions

    When using JavaScript in conditions, the editor provides access to specific tokens that are typically related to input data and certain system variables. These may include:

    • Input Data Tokens: Tokens representing user-provided parameters or external source data. Example: {{.customInput.userId}}

    • System Variables: Tokens for accessing system-related data like current time or user session. Example: {{.systemVar.currentTime}}

    • Global Variables: Tokens that provide access to predefined global values. Example: {{.globalVar.taxRate}}

    • Data Set Tokens: Tokens linked to particular data sets relevant to the rule's logic. Example: {{.dataSet.salesFigure}}

  2. Tokens in Results

    In the context of results, tokens generally pertain to output data and other computed values that result from the script's execution:

    • Output Data Tokens: These tokens encapsulate the results of data processing and can be used to construct response payloads or guide subsequent operations. Example: {{.outputData.finalPrice}}

    • Input Data Tokens: Tokens representing user-provided parameters or external source data. Example: {{.customInput.userId}}

    • System Variables: Tokens for accessing system-related data like current time or user session. Example: {{.systemVar.currentTime}}

    • Global Variables: Tokens that provide access to predefined global values. Example: {{.globalVar.taxRate}}

    • Data Set Tokens: Tokens linked to particular data sets relevant to the rule's logic. Example: {{.dataSet.salesFigure}}

For a detailed list of available tokens, their specific uses, and examples in different contexts, users are encouraged to refer to the official Nected documentation on pre-configured tokens. This comprehensive guide can be found at: Nected Pre-configured Tokens Documentation.

By understanding and effectively utilizing these tokens in their respective contexts, users can significantly enhance the functionality and efficiency of their scripts within the Nected custom editor.

Usage Examples

The custom editor in Nected has some practical applications that can be leveraged in real-world scenarios. Here’s an overview of its current functionalities of our Custom Editor:

  1. Multi-Language Support:

    The editor supports several programming languages, including JavaScript (JS), JSON, MySQL, PostgreSQL, and Mongo. This wide range of language support makes it versatile for various types of data handling and scripting needs.

  2. Real-Time Linter:

    The inclusion of a real-time linter is crucial for maintaining code quality. It helps in identifying and correcting syntax errors as the code is being written, greatly reducing debugging time and enhancing code reliability.

  3. Autocomplete Functionality: The custom editor provides an autocomplete feature that suggests relevant code snippets and tokens as the user types. This is particularly useful when writing complex queries or functions, as it helps to complete statements with fewer keystrokes and reduces the chance of syntactical errors. For example, when a user types "re", the editor will display all the options containing "re", aiding in faster coding.

  4. Token Integration:

    Tokens in the editor act as dynamic placeholders in the code, allowing for flexible data manipulation. Their integration is especially useful in environments where the code interacts with variable data inputs.

  5. Visual Distinction of Elements:

    The editor enhances readability by color-coding different elements, such as displaying tokens in blue. This visual distinction aids in quick identification and understanding of various components within the code.

Below are some examples of how the editor's features can be used to create efficient workflows within Nected using the current features.

Code Examples

In the custom editor, you can create formulas and DB queries like the below:

  1. Dynamic Price Calculation:

    // Calculate total price with dynamic tax rate
    let totalPrice = {{.customInput.basePrice}} * (1 + {{.globalVar.taxRate}});
    totalPrice.toFixed(2);

    In this example, the editor helps calculate the total price of an item by retrieving the base price and applying a dynamic tax rate. Autocomplete aids in quickly finding the right tokens, and the real-time linter ensures that the code is error-free.

  2. Database Query for Order Processing:

    // Retrieve pending orders for processing
    SELECT * FROM orders WHERE status = 'pending' AND orderDate >= {{.systemVar.StartDate}};

    A user can write SQL queries directly in the editor to interact with databases. This is useful for extracting specific data, such as pending orders since a certain start date, which can be dynamically inserted through tokens.

Error Handling and Troubleshooting

Effective error handling and troubleshooting are crucial in any coding environment. Nected's custom editor incorporates several features to assist users in identifying and resolving issues that may arise during the development process.

Common Errors and Solutions

  1. Syntax Errors:

    The real-time linter in the editor flags syntax errors as the code is being written. Users should pay attention to these prompts to correct mistakes on the fly.

  2. Token Mismatch:

    When tokens are typed manually and mismatched, the autocomplete feature might not provide the correct suggestions, leading to errors. Users should select tokens from the autocomplete suggestions to mitigate this issue.

Best Practices for Troubleshooting

  1. Using Autocomplete:

    Always use the autocomplete feature to insert tokens, function names, and other code elements to reduce errors.

  2. Testing in Segments:

    Break down your code into smaller segments and test each part individually to isolate and identify errors more efficiently.

  3. Reviewing Token References:

    Regularly review the list of available tokens and their correct usage on the official Nected Pre-configured Tokens documentation to ensure you're using the right tokens for the intended purpose.

Handling Null and Undefined Values

Currently, the editor blocks returns of null or undefined to prevent runtime errors. However, future updates will provide warnings instead, offering a more forgiving error-handling approach while still guiding users towards best practices.

Missing Parameter Best Practices

To avoid issues with missing parameters, refrain from typing tokens or parameters manually. While writing, check it on the editor's autocomplete feature to ensure the correct use of pre-configured tokens and to prevent the use of non-existent tokens, which would result in an error.

By following these guidelines for error handling and troubleshooting, users can efficiently navigate the custom editor environment, minimize disruptions, and maintain a smooth coding experience within Nected.

Null and Missing Parameter Handling

In programming, particularly within dynamic environments such as Nected's custom editor, the handling of null and missing parameters is a critical aspect of ensuring robust and error-free code execution. Here’s how Nected addresses these scenarios and the best practices users should adopt.

Null Parameter Handling

In Nected's custom editor, handling null parameters within JavaScript code is essential to ensure smooth execution and to avoid runtime errors. When a null or undefined value is encountered in the midst of a script, it may lead to unintended behaviors or errors. Here are best practices and strategies to effectively handle null parameters:

  1. Checking for Null or Undefined Values

    Before using a variable or parameter in your code, it's crucial to check if it's null or undefined. This precaution helps prevent errors that could arise from attempting to access properties or call methods on null objects.

    if ({{.customInput.someParameter}} !== null && {{.customInput.someParameter}} !== undefined) {
        // Code to execute if someParameter is neither null nor undefined
    }

    In this example, the script checks whether someParameter is null or undefined before proceeding with operations that depend on it.

  2. Providing Default Values

    Assigning default values to variables or parameters that might be null is a proactive way to maintain the flow of your script. This approach ensures that your code can continue to execute even if some expected data is missing.

    let parameterValue = {{.customInput.someParameter}} || 'default value';

    Here, parameterValue is assigned a default value if someParameter is null or undefined.

  3. Null Coalescing Operations

    JavaScript's nullish coalescing operator (??) can be used to provide default values more concisely.

    let parameterValue = {{.customInput.someParameter}} ?? 'default value';

    This example achieves the same result as the previous one but uses the nullish coalescing operator for brevity.

  4. Handling Null in Function Parameters

    If a function might receive null parameters, it's advisable to include checks or default assignments within the function.

    function processData(parameter) {
        let processedParameter = parameter ?? 'default value';
        // Processing logic using processedParameter
    }

    This function assigns a default value to processedParameter if parameter is null.

Impact of Null Parameters in Scripts

Scripts that fail to handle null parameters appropriately may result in errors or unexpected behavior, especially if the script tries to access properties or methods of a null object. The custom editor in Nected may also display warnings or errors if it detects potential null reference issues like this: The statement written here is syntactically incorrect or returns null/undefined value. Please handle null or undefined cases in your code.

By following these best practices for null parameter handling in JavaScript, users can write more robust and error-resistant code within Nected's custom editor, ensuring smoother application functionality and enhancing overall code reliability.

Missing Parameter Handling

In Nected's custom editor, managing missing parameters is crucial, especially when dealing with optional fields or dynamic data structures. When a parameter expected by the JavaScript code is missing, it could lead to unexpected behaviors or errors during script execution. Here's how to handle such scenarios effectively:

Understanding Optional Parameters in Rules

When a parameter is marked as optional in a rule, it means that it may or may not be present during the execution of the JavaScript code. The absence of these parameters should be anticipated and handled gracefully in the script to avoid disruptions in the application's functionality.

Best Practices for Handling Optional Parameters

  1. Checking for Undefined or Missing Values: Before using a parameter, check if it is undefined or missing. This can prevent errors related to accessing properties of undefined objects.

    Example:

    if (typeof {{.customInput.optionalParameter}} !== 'undefined') {
        // Execute logic if optionalParameter exists
    }

    This check ensures that the code within the if block only runs if optionalParameter is present.

  2. Graceful Degradation: Design your code to degrade gracefully if an optional parameter is missing. This approach involves having a default behavior or value that the script reverts to in the absence of the parameter.

    Example:

    let parameterValue = {{.customInput.optionalParameter}} || 'default behavior';

    Here, parameterValue takes on a default value or behavior if optionalParameter is missing.

  3. Using Fallback Logic: Implement fallback logic within your code to handle scenarios where optional parameters are not provided.

    Example:

    function handleData(parameter) {
        if (parameter) {
            // Logic for when parameter is provided
        } else {
            // Fallback logic
        }
    }

    This function has distinct paths based on the presence of the parameter.

  4. Conditional Feature Execution: In cases where certain features of your application rely on optional parameters, use conditional checks to execute these features only when the parameters are available.

    Example:

    if ({{.customInput.optionalFeatureParameter}}) {
        // Execute feature logic
    }

    The feature logic here runs only if optionalFeatureParameter is available.

Impact on JavaScript Execution

If the script fails to account for missing optional parameters, it may lead to incomplete executions, errors, or unhandled exceptions. Proper handling ensures that the script continues to operate effectively even when some data is absent.

By incorporating these best practices into their JavaScript code within the Nected editor, users can create more resilient applications that can adapt to varying data availability, ensuring a seamless user experience regardless of the presence or absence of optional parameters.

Troubleshooting Steps:

When null or undefined values are returned, or if a non-existing token is used, the editor will block the user and present an error. This immediate feedback loop helps users identify and correct issues promptly.

  1. Review Error Messages: Analyze the error messages provided by the editor to understand what is causing the block.

  2. Check Token Validity: Verify that the tokens used are correct and exist within the system.

  3. Read Documentation: Read the official documentation to know what to write and how to write properly.

Looking ahead, Nected plans to implement a system where warnings will be issued for null returns rather than outright blocks, giving users more leeway to handle null values according to their specific use case requirements. This change will encourage users to consider the implications of null values in their code while still allowing them the flexibility to manage these scenarios as they see fit.

By adhering to these best practices for handling null and missing parameters, users can ensure that their code in Nected's custom editor is robust, reliable, and less prone to runtime errors.

Conclusion

The Formula and Custom JavaScript Editor in Nected is a versatile solution for complex business requirements, extending beyond no-code capabilities. It enables users to create intricate logical conditions, manage detailed outputs, and perform data manipulation and transformation. With its tokenized system, users can easily integrate custom inputs, datasets, and output data for diverse applications. Designed for Nected's varied user base, this tool is accessible for both non-technical users and more experienced developers or data analysts. It exemplifies Nected’s commitment to providing a flexible, user-friendly platform for advanced customization and detailed rule configurations.

Last updated