JavaScript Editor

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

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

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

Formula, using tokens, can be written by any person, irrespective of tech know-how, however if you need to write little complex logic, it can come handy for developers and analyst.

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.

  3. Fetching External Data for Conditions:

    JavaScript can be used to dynamically incorporate external data into conditions, allowing conditions to adapt based on real-time data.

    let hasValidAccount = {{.dataSet.account_id}} !== null;
    if (hasValidAccount) {
        rest_api_connector({
          connectorName: 'Test',
          urlPath: '',
          method: 'POST',
          body: '',
          headers: { 'Content-Type': 'text/csv' },
          queryParams: {}
        });
        // Additional logic based on API response
    } else {
        false;
    }
    hasValidAccount;
    

    In this scenario, an external API is called if the account ID exists. The condition then adapts based on the presence of an account ID and the response from the API call.

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. Fetching External Data for Manipulation or Calculation:

    JS is used to fetch and then process external data for either transforming it or performing calculations.

    // Example: Calculate price with dynamic currency rates
    rest_api_connector(select_connector);
    let priceInUSD = {{.cusotmInput.productPrice}};
    let convertedPrice = priceInUSD * externalData.currencyRate;
    convertedPrice.toFixed(2);
    
  4. 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.

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. REST API Integration:

    A significant feature within the editor is the ability to integrate and utilize REST APIs. The format for this functionality is expressed as rest_api_connector(select_connector);. Users can click on the select_connector placeholder to choose from a list of previously created and integrated connector APIs. This seamless integration allows for the straightforward execution of RESTful services within the editor environment.

  6. 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.

  3. REST API Call for Data Integration:

    // Fetch user details from a REST API
    rest_api_connector(connectorName='Zapier', urlPath='', method='GET', body={}, headers={'Content-Type': 'application/json'}, queryParams={}); 
    /*
      * The response structure to the API is:
      *     response.Body  - {Object}
      *     response.Headers - {Object}
      *     response.StatusCode - {Number}
      *     response.error - {String}
    */

    This snippet shows how a user can incorporate REST API calls within their code. Like shown in the previous section, after selecting a specific API, user can see this kind of code. Now, they can edit this as per their requirements.

Features Coming Soon

While the custom editor in Nected currently boasts a range of functionalities, there are additional features on the horizon that are expected to further elevate the user experience:

  1. Enhanced Autocomplete:

    The forthcoming enhanced autocomplete will refine the current functionality by narrowing down the suggestions to the most relevant options based on the context of the code being written. For instance, when a user starts typing "rest_api_", instead of showing all possible options that include "re", the editor will specifically suggest rest_api_connector(select_connector);, which directly relates to connecting a REST API. This targeted suggestion streamlines the coding process by providing contextually appropriate options, reducing clutter and improving efficiency.

  2. IntelliSense:

    The introduction of IntelliSense is another anticipated feature. It will provide smart completions based on variable types, function definitions, and imported modules, offering a more sophisticated and context-aware coding experience.

Here are few scenarios where using the Editor could be beneficial for the user:

  1. Customer Segmentation: Using JavaScript within the editor, a user can segment customers based on their purchase history and demographics, dynamically pulling data from various sources and applying custom logic to categorize customers.

  2. Inventory Management: SQL queries can be crafted to manage inventory levels by checking stock and reordering items when quantities fall below a certain threshold, directly interacting with the database.

  3. Automated Reporting: JSON structures can be defined in the editor to create automated reports that pull data from different parts of the system, using tokens to represent real-time figures, and then send this data through REST APIs to other platforms or stakeholders.

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.

  3. REST API Connector Errors:

    If the REST API connector function is not set up correctly, or if the selected connector is not properly configured, the editor will fail to execute the API call. Ensure that the REST API has been integrated correctly via the Nected connector.

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 in a more concise manner.

    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