JavaScript Code by Pabbly

Status
Not open for further replies.
You may expand the functionality of your Pabbly Connect workflow by using the most widely used web programming language, Javascript, with Code by Pabbly: JavaScript action.

Some example 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.
  • Execute Javascript functions and relevant code.
Warning - This step involves programming, so beware! 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.

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.
  • Your code will be wrapped in an async function.
  • The wrapper function has some pre-defined constants, namely CryptoJS, _, and moment and pre-defined variables 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 below screenshot of executing the above code

1669452362870.png


2. Returning Statements:


You can bind the resulting statement of the code either to the `output` variable or simply using the `return` statement as shown in the example:
The variable output has already been declared in the wrapper function.

JavaScript:
output = JSON.stringify({"totalPrice":totalPrice});

JavaScript:
return JSON.stringify({"totalPrice":totalPrice});


3. Introductory Logging Example
The following console methods are available for logging purposes: log, warn, error and debug.
JavaScript:
let name = "john";

if (name != "") {
console.log('got name!', name);
}

return {id: 1234, hello: 'world!', name: name};

1669444600709.png



4. Mathematical Expression - Divide by Five
JavaScript:
let num = 125;
return {
  result: Number(num)/5
};

1669444972967.png


5. 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._-][email protected][\w._-]+\.[\w._-]+)/gi) || [])[0]
};

1669445447541.png


6. 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&[email protected]",
requestOptions) .then(response => response.json()) .then(result => result.data) .catch(error => console.log('error', error));

1669379952763.png


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));

1669446127750.png


7. Available JavaScript libraries with Examples

- 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()
};

1669451133566.png


- 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
};


1669450822226.png


- 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 });

1669448308325.png
 

Attachments

  • 1669377435416.png
    1669377435416.png
    40.4 KB · Views: 24
  • 1669380295937.png
    1669380295937.png
    40.9 KB · Views: 35
  • 1669445971237.png
    1669445971237.png
    46.2 KB · Views: 21
Last edited:
Status
Not open for further replies.
Top