JavaScript Editor
Last updated
Last updated
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.
Now, using the Javascript Editor inside a rule and a workflow is pretty simple. The Formula editor is available inside:
Rule:
Rule Conditions
Rule Result
Workflow:
Code Node
In SetVariable node
Response node
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.
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.
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.
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.
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.
Mathematical Formulas for Deriving Values:
For straightforward calculations, such as financial computations, users can implement formulas directly.
Transforming/Manipulating Data:
More sophisticated data manipulation requires full JS code to parse, transform, or combine data points.
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.
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.
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.
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.
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.
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
Set Variable Node
Response Node
Code 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
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.
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.
Custom Function Scripting:
Write your custom logic in the JS Code Editor.
you can Integrate custom tokens and predefined macro functions to create custom conditions and aggregations for better business decisions.
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
.
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.
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
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.
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.
Custom Function Scripting:
Write your custom logic in the JS Code Editor .
you can Integrate custom tokens and predefined macro functions to create custom conditions and aggregations for better business decisions.
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
.
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.
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.
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.
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
Custom Function Scripting:
Write your custom logic in the JS Code Editor.
Integrate custom tokens and predefined macro functions to create custom conditions and aggregations for better business decisions.
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
.
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.
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:
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}}
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.
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:
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.
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.
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.
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.
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.
In the custom editor, you can create formulas and DB queries like the below:
Dynamic Price Calculation:
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.
Database Query for Order Processing:
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.
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.
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.
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.
Using Autocomplete:
Always use the autocomplete feature to insert tokens, function names, and other code elements to reduce errors.
Testing in Segments:
Break down your code into smaller segments and test each part individually to isolate and identify errors more efficiently.
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.
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.
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.
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.
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:
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.
In this example, the script checks whether someParameter
is null or undefined before proceeding with operations that depend on it.
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.
Here, parameterValue
is assigned a default value if someParameter
is null or undefined.
Null Coalescing Operations
JavaScript's nullish coalescing operator (??
) can be used to provide default values more concisely.
This example achieves the same result as the previous one but uses the nullish coalescing operator for brevity.
Handling Null in Function Parameters
If a function might receive null parameters, it's advisable to include checks or default assignments within the function.
This function assigns a default value to processedParameter
if parameter
is null.
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.
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:
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.
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:
This check ensures that the code within the if
block only runs if optionalParameter
is present.
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:
Here, parameterValue
takes on a default value or behavior if optionalParameter
is missing.
Using Fallback Logic: Implement fallback logic within your code to handle scenarios where optional parameters are not provided.
Example:
This function has distinct paths based on the presence of the parameter
.
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:
The feature logic here runs only if optionalFeatureParameter
is available.
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.
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.
Review Error Messages: Analyze the error messages provided by the editor to understand what is causing the block.
Check Token Validity: Verify that the tokens used are correct and exist within the system.
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.
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.