Introduction
The Canonic Code Editor is an embedded JavaScript editor for writing custom logic within your workflows. It is available within Function and Output nodes.
Features
- Asynchronous Support: Write asynchronous JavaScript functions to handle operations that require waiting for execution.
- Parameter Access: Easily access input parameters and the output of previous nodes in your workflow.
- Syntax Highlighting: The editor provides syntax highlighting to improve the readability of your code.
- Error Detection: Real-time error detection helps to identify issues quickly.
Accessing Parameters
In the Code Editor, you can access the workflow's parameters as follows:
/**
* @param {Object} params - Object containing parameters
* @param {Object} params.input - The input object
* @param {Object} params["1"].output - Output of the first node of the workflow
**/
Writing Code
When utilizing the Code Editor, adhere to the following best practices:
- Comment Your Code: Provide clear comments within your code to explain the logic and functionality, making it maintainable and understandable for others or for future reference.
- Error Handling: Implement robust error handling to gracefully manage exceptions, ensuring your workflow behaves predictably under all conditions.
- Testing: Leverage the built-in testing tools provided by Canonic to rigorously test your code before deployment.
Testing and Deployment
Prior to deployment:
- Test Thoroughly: Use Canonic's testing features to confirm that your code performs as expected across all scenarios.
- Handle Inputs Carefully: Make sure that your code correctly handles all the inputs it may receive.
Example
Imagine you need to validate user input within a workflow:
- Open the Code Editor in a Function node.
- Access the user input using
params.input
. - Write a JavaScript function to validate this input, for example, checking if an email address is correctly formatted.
module.exports = async function (params) {
const email = params.input.email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(email)) {
throw new Error("Invalid email format")
}
return { valid: true }
}
This function checks if the provided email adheres to a basic format. If it doesn't, it throws an error; otherwise, it returns an object indicating the input is valid.
Note: It's crucial to conduct comprehensive testing and to handle sensitive data with care to preserve the integrity and security of your application.