Introduction
You can extend the functionality of your Pabbly Connect workflow by using the most widely used web programming language, JavaScript, with Code by Pabbly : JavaScript action.
Some of use cases include:
Note: The environment is Node.js v18.x which runs AWS SDK for JavaScript v3. Your code can only run for a limited amount of time i.e. up to 25 seconds and within a limited amount of memory i.e. up to 128MB. If you exceed those limits - your script will be killed.
Section 1.
Variable and function declarations
Inside Code by Pabbly: JavaScript module, you can declare the variables as you do in JavaScript basic programming using `let`, `const`, `var` depending upon your need.
Here is a sample JavaScript code with which, you can get the idea of using variables and performing operations on them to return the desired output.
Check the screenshot below of executing the above code:
Check the screenshot below of executing the above code:
Section 2.
Return a value: obtain the final output/result of the execution
The returned a value will be available under the label Output in the step Response.
You have two ways to return your required value - using a return statement, using the `output` variable instead of a return statement. Follow any one of them, as demonstrated below.
Notice that the outcome (the step Response) is the same.
Section 3.
Logging: printing a variable for testing/debugging
Logging is optional. In order to check (print) intermediate values of the execution, you can use the following console methods:
All the printings by these methods will be visible under the label Logs in the step Response.
Section 4.
Example: Mathematical Expression - divide by five
Section 5.
Example: Using Regex to extract emails from given string
Section 6.
Example: Use fetch()
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
GET API Call Example
POST API Call Example
Section 7.
Available JavaScript libraries
The module has been reinforced with three popular JavaScript libraries, namely CryptoJS, Lodash, and Moment. These libraries are ready to access through our pre-defined identifiers
For a detailed explanation of how to use Code (Pabbly), please refer to the video below:
You can extend the functionality of your Pabbly Connect workflow by using the most widely used web programming language, JavaScript, with Code by Pabbly : JavaScript action.
Some of use cases include:
- Date transformations or data type conversions.
- Use custom regular expressions to extract data like emails or tracking numbers from large text blobs.
- Make an extra API call to a different service with fetch without building a full dev app.
- Process your data in a way that you think is better than other apps onboard.
- Do your personalized processing or calculations which aren’t currently possible with other apps.
- Perform multiple tasks in a single step.
Warning - This step involves programming, so be careful! To use this, you probably need to be a coder, though you are welcome to play about with it. There is no technical help for errors in your code!
Note: The environment is Node.js v18.x which runs AWS SDK for JavaScript v3. Your code can only run for a limited amount of time i.e. up to 25 seconds and within a limited amount of memory i.e. up to 128MB. If you exceed those limits - your script will be killed.
Section 1.
Variable and function declarations
Inside Code by Pabbly: JavaScript module, you can declare the variables as you do in JavaScript basic programming using `let`, `const`, `var` depending upon your need.
- Entire content you write in or enter into the JavaScript Code field is internally wrapped in an async function, like this:
JavaScript:async function name() { // Predefined constants to use 3 popular libraries. (Ref.: section 7):- const CryptoJS = …; const _ = …; const moment = …; // Pre-declared variable:- var output; // Your code:- ... ... ... ... ... ... return output; }
- The wrapper function has some predefined constants, namely CryptoJS, _, and moment and a predefined variable, namely output.
- You can use await keyword if required.
Here is a sample JavaScript code with which, you can get the idea of using variables and performing operations on them to return the desired output.
JavaScript:
//initializing variables
let data = {
"first_name": "Pabbly", "last_name": "Connect", "invoice_id": 123456, "total_price": 55.50, "line_items": [ { "product_id": 123, "name": "world", "price": 5.50 }, { "product_id": 234, "name": "planet", "price": 11.00 } ] };
let lineItems = data.line_items;
let totalPrice = 0;
//Javascript loop
for (let i = 0; i < lineItems.length; i++) {
totalPrice += lineItems[i].price;
};
//Output or returning result
return JSON.stringify({"totalPrice":totalPrice});
Check the screenshot below of executing the above code:
- Using the same structure with mapped fields.
JavaScript:
let data = {
"Name": "1. Name : JohnDoe",
"last_name": "Connect",
"Invoice_Id": "1. Invoice Id : 123456",
"Total_Price": "1. Total Price : 55.50",
"line_items": [
{ "product_id": 123, "name": "world", "price": 5.50 },
{ "product_id": 234, "name": "planet", "price": 11.00 }
]
};
let lineItems = data.line_items;
let totalPrice = 0;
// JavaScript loop
for (let i = 0; i < lineItems.length; i++) {
totalPrice += lineItems[i].price;
}
// Output or returning result
let result = {
totalPrice: totalPrice,
lineItems: lineItems
};
console.log(JSON.stringify(result));
Check the screenshot below of executing the above code:
Section 2.
Return a value: obtain the final output/result of the execution
The returned a value will be available under the label Output in the step Response.
You have two ways to return your required value - using a return statement, using the `output` variable instead of a return statement. Follow any one of them, as demonstrated below.
2.1. Using a return statement:
JavaScript:
// Convert a given paragraph to uppercase and then extract sentences from it:-
var para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.';
var modification1 = para.toUpperCase();
var modification2 = modification1.replaceAll('. ', '.*');
var sentences = modification2.split('*');
return sentences;
- Using the same structure with mapped fields.
Note: Ensure that the value mapped from the above event adheres to the proper code structure, including clearly defined keys and corresponding values.
2.2. Using the `output` variable instead of a return statement:
Assign your required value to our pre-declared variable `output`. The last assigned value of output will be returned as your execution result.
JavaScript:
// Convert a given paragraph to uppercase and then extract sentences from it:-
var para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.';
var modification1 = para.toUpperCase();
var modification2 = modification1.replaceAll('. ', '.*');
output = modification2.split('*');
Notice that the outcome (the step Response) is the same.
Section 3.
Logging: printing a variable for testing/debugging
Logging is optional. In order to check (print) intermediate values of the execution, you can use the following console methods:
log()
, error()
, warn()
, and debug()
.All the printings by these methods will be visible under the label Logs in the step Response.
JavaScript:
// Convert a given paragraph to uppercase and then extract sentences from it:-
var para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.';
var modification1 = para.toUpperCase();
console.log(modification1); // logging
var modification2 = modification1.replaceAll('. ', '.*');
var sentences = modification2.split('*');
console.log(JSON.stringify(sentences)); // logging
return sentences; // the output (result)
Tip:
To print an array or object, stringify it first.
JavaScript:
console.log(JSON.stringify(sentences));
- Using the same structure with mapped fields.
Important:
Logging option is not for obtaining the final output of the workflow step. To obtain the final output follow Section 2 above.
Section 4.
Example: Mathematical Expression - divide by five
JavaScript:
let num = 125;
return {
result: Number(num)/5
};
- Using the same structure with mapped fields.
Section 5.
Example: Using Regex to extract emails from given string
JavaScript:
let string = "Here are the emails [email protected], [email protected] and [email protected]";
return {
Emails: (string.match(/([\w._-]+@[\w._-]+\.[\w._-]+)/gi) || [])[0]
};
- Using the same structure with mapped fields.
Section 6.
Example: Use fetch()
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
GET API Call Example
JavaScript:
//Defining headers
var myHeaders = new Headers();
//Initializing header with required values like, API Key, Content type etc.
myHeaders.append("X-API-Key", "HE48Q2LUVB6OXXXXXX5BARMGUSHS");
myHeaders.append("X-Account-Name", "MyAccount");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
//Return statement with fetch function
return fetch("https://api.newzenler.com/api/v1/users?limit=1&search=john.doe@gmail",
requestOptions) .then(response => response.json()) .then(result => result.data) .catch(error => console.log('error', error));
POST API Call Example
JavaScript:
//Defining headers
var myHeaders = new Headers();
//Pass specific headers if required like, API Key, Token, Content Type etc..
myHeaders.append("x-api-key", "XLgggHyhde887887");
myHeaders.append("Content-Type", "application/json");
//API request body JSON payload
var raw = JSON.stringify({
"name": "John Doe",
"email": "[email protected]",
"phone": "877878898"
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw, redirect: 'follow'
};
//Return statement with fetch function
return fetch("https://webhook.site/059ceed3-7545-4f8f-9852-e7023ce6f4a9", requestOptions) .then(response => response.text()) .then(result => result) .catch(error => console.log('error', error));
Section 7.
Available JavaScript libraries
The module has been reinforced with three popular JavaScript libraries, namely CryptoJS, Lodash, and Moment. These libraries are ready to access through our pre-defined identifiers
CryptoJS
, _
, and moment
respectively.7.1 CryptoJS
CryptoJS is a growing collection of standard and secure cryptographic algorithms like, MDF, SHA1, SHA2, AES, HMAC, etc. implemented in JavaScript using best practices and patterns.
JavaScript:
//initialize varaibales
var public_api_key = "7e151e4060d6497111ed15565351b4332";
var secret_key = "8ad52a1d5d619835566a3848f3a6edg";
//Getting current timestamp
var timestamp = Math.floor(new Date().valueOf()/1000);
//Calculating hash HMAC using CryptoJs
var hash = CryptoJS.HmacSHA1(public_api_key + timestamp, secret_key);
//Returning the output
return {
"public_api_key":public_api_key, "timestamp":timestamp, "hash":hash.toString()
};
- Using the same structure with mapped fields.
7.2. Moment.js
A JavaScript date library for parsing, validating, manipulating, and formatting dates.
JavaScript:
let now = moment().format('LLLL');
let locale = moment.locale();
let format = moment("10/08/2022").format("MM-DD-YYYY");
let day = moment("2022-10-08").format("dd");
output = {
"now":now,
"locale":locale,
"format":format,
"day":day
};
- Using the same structure with mapped fields.
7.3 Lodash
Lodash is a JavaScript library that works on the top of underscore.js. It helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach which that coding in JavaScript easier to understand because instead of writing repetitive functions, tasks can be accomplished with a single line of code.
JavaScript:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
// the `_.matches` iteratee shorthand.
return _.filter(users, { 'age': 36, 'active': true });
- Using the same structure with mapped fields.
Troubleshooting
Problem | Possible Cause | Solution |
---|---|---|
In automation my Code step shows Error: SyntaxError: Invalid or unexpected token . If I copy the sent code from the Task History ('Data In' tab), and paste it into a Code input field, it runs fine. | The data you pass to Code contains: HTML tags and/or line breaks within strings wrapped with "" or '' . | Before using in Code, sanitize your data with the following actions.
`` wrapped strings won't break the syntax.
Code:
Note: line breaks in `` wrapped strings won't break the syntax in JSON.
Code:
|
My Code step shows Logs, but not the output. | Missing a return or output statement in right place. | You have two ways to obtain (return) your required value. If you want to obtain the value of x, write any one of the following statements:
See demos in Section 2 of this guide. |
My Code works sometimes, but sometimes doesn't. |
| |
For a detailed explanation of how to use Code (Pabbly), please refer to the video below:
Attachments
Last edited by a moderator: