Skip to main content
All CollectionsFunctions
How to use LayerScript® Extensions
How to use LayerScript® Extensions

An article explaining how to use the helpers included in LayerScript to perform complex operations with ease

Nick Kewney avatar
Written by Nick Kewney
Updated over 3 years ago

If you haven't read Extend Layer functionality with Scriptable Functions, it might be worth checking this out before reading this reference.


LayerScript Extensions are a collection of useful functions which abstract some of the complexity of coding for some basic functions like sending system emails, or calculating rate tables.

  • ScriptableFunctionHttpRequest

  • ScriptableFunctionLookupTable

  • ScriptableFunctionLogger

  • ScriptableFunctionEncoder

  • ScriptableFunctionOAuthHelper

  • ScriptableFunctionMailer

  • ScriptableFunctionJsonToHtml 🆕

  • ScriptableFunctionSlackClient 🆕


ScriptableFunctionHttpRequest

This extension carries out all the legwork to make an HTTP call to third-party or Layer APIs. It supports POST, PUT and GET and can prepare payloads in JSON and XML (coming soon).

Example 1: Iterate through a result form an API GET

// STEP 1: Define an empty string to contain the result

var result = "";
// STEP 2: Initiate a ScriptableFunctionHttpRequest()

var request = new ScriptableFunctionHttpRequest(); // Special type to make HTTP calls

request.AddHeader("Token1", "xx"); request.AddHeader("Token2", "xx");

// STEP 3: Read from the URL
var item = request.Get('https://webapi.thelayer.com/', 'api/Category/GetCaseCategories', 'application/json'); // Tip: itemId & typeId are in context'
// STEP 4: Parse the results as JSON

var json = JSON.parse(item);
// STEP 5: Iterate through the results and append to the result variable

for (var i = 0; i < json.length; i++) { var obj = json[i]; result = result + obj.CategoryName + ' '; }

// STEP 6: Return the result
return result;

Example 2: Look up a value from API

var request = new ScriptableFunctionHttpRequest();

request.AddHeader("Token1","xx");
request.AddHeader("Token2","xx");
var json = JSON.parse(request.Open('https://webapi.thelayer.com/', 'api/Lease/Lease?id='+itemId, 'application/json'));
var total = 0;

for (var i = 0; i < json.Associations.length; i++) {
var association = json.Associations[i];
if (association.ProductSupplier.Name == "EE") total = total + association.CostOngoing;
}
return total.toFixed(2);

Example 3: Connect to our API, grab a new Mail Triage item and send an email based on the content

var request = new ScriptableFunctionHttpRequest(); 

// Authenticate

request.AddHeader("Token1","xx");
request.AddHeader("Token2","xx");
// Fetch Item
var mailTriageItem = JSON.parse(request.Get('https://webapi.thelayer.com/', 'api/MailTraigeMessage/GetMailMessage?msgId=01e3cc8280ff4222a94fbe0bf996d089', 'application/json'));
// Build Mail Agent Message

request.AddFormValue("MailAgentId", 0);
request.AddFormValue("ToCollection", "0");
request.AddFormValue("CCAddressCollection", "");
request.AddFormValue("BCCAddressCollection", "");
request.AddFormValue("HasBranding", false);
request.AddFormValue("SendAfter", "2020-04-22T14:37:17.902Z");

// Send Message
if (mailTriageItem.Data.Subject.indexOf("Job") !== -1) // If the subject contains 'Job'
{
request.AddFormValue("Subject", mailTriageItem.Data.Subject);
request.AddFormValue("Body", mailTriageItem.Data.Body);
request.Post('https://webapi.thelayer.com/', 'api/Mail/Send', 'application/json'); // Send the mail
}

// Return the subject

return mailTriageItem.Data.Subject;

Example 4: Raise a case from a sales order

// Step 1: Set up the API Request  
var request = new ScriptableFunctionHttpRequest();

// Step 2: Authenticate
request.AddHeader("Token1","x");
request.AddHeader("Token2","x");

// Step 3: Fetch Sales Order
var order = JSON.parse(request.Get('https://webapi.thelayer.com/', 'api/SalesOrder/GetSalesOrderById?id='+itemId, 'application/json'));

// Step 4: Build Case
request.AddFormValue("CustomerId", order.CustomerId);
request.AddFormValue("SalesOrderId", order.ID);
request.AddFormValue("Subject", order.Reference);
request.AddFormValue("Body", order.Reference);
request.AddFormValue("CategoryId", 0);
request.AddFormValue("SubCategoryId", 0);
request.AddFormValue("StatusId", 8);
request.AddFormValue("ContactId", null);
request.AddFormValue("Owner", null);
request.AddFormValue("SendNotification", false);
request.AddFormValue("CaseTypeId", 1); // Case Type, 1 = Case, 2 = Job
request.AddFormValue("OpportunityId", order.OpportunityId); // Optional

// Step 5: Create Case var response = request.Post('https://webapi.thelayer.com/', 'api/Cases/CreateCase', 'application/json'); // Create Case

// Step 6: Return HTTP Response (Just for Test!)
return response;

Or send a message to Teams channels:

var request = new ScriptableFunctionHttpRequest();
var post =
{
"@context": "https://schema.org/extensions",
"@type": "MessageCard",
"potentialAction": [
{
"@type": "OpenUri",
"name": "View Sales Order",
"targets": [
{
"os": "default",
"uri": "https://meow.com"
}
]
}
],
"sections": [
{
"facts": [
{
"name": "Reference:",
"value": "ORD-1234-BM"
},
{
"name": "Customer:",
"value": "My Customer Limited"
},
{
"name": "Opportunity:",
"value": "Special Fun Opportunity"
}
],
"text": "A sales order has just been created:"
}
],
"summary": "Order Created",
"themeColor": "0072C6",
"title": "Order Created"
}

request.SetBody(JSON.stringify(post));

var item = request.Post('https://layer.webhook.office.com/', 'xxx', 'application/json'); // Tip: itemId & typeId are in context'

return "";


ScriptableFunctionLookupTable

This is a pretty complex function, and lets you define a lookup table, as per the example below.

Define the Y-axis headers, the X-axis rows, then use "Lookup()" to obtain the matching values! Great for range-based calculations.

// JS 3D Table Lookup Helper

var table = new ScriptableFunctionLookupTable("24,36,48,60,72,84"); // Define Y-axis headers
table.Add(1000, "934.9229,976.455,1017.357,1063.101,1106.709,1152.34116");

// Define rows
table.Add(5000, "6205.079,6421.821,6671.369,6930.712,7185.0575,7450.88398"); table.Add(10000, 12404.89,12799.06,13281.81,13752.91,14275.663,14788.9355"); table.Add(20000, "24797.38,25533.28,26402.77,27413.52,28362.444,29346.209"); table.Add(50000, "61967.09,63788.15,65711.26,68149.03,70420.97,72801.7615"); table.Add(100000, "0,0,0,0,0");

return table.Lookup(5001, 36); // Perform lookup


ScriptableFunctionLogger

Log to our dedicated logging platform to your heart's content. Don't forget the "return" value will always be logged as a result.

Example 1: Simple log

var logger = new ScriptableFunctionLogger(functionId);

logger.WriteLog('I am a log entry');

Example 2: Post log

var logger = new ScriptableFunctionLogger(functionId);

logger.WriteLog(request.ToString());


ScriptableFunctionEncoder

This one's really useful for OAuth and other purposes. It helps you convert a string to Base64.

var encoder = new ScriptableFunctionEncoder(functionId);

var encodedString = encoder.ToBase64String("string");


ScriptableFunctionOAuthHelper

var encoder = new ScriptableFunctionEncoder();
var authInfo = '[email protected]:xyz';
var authBase64 = encoder.ToBase64String(authInfo);


ScriptableFunctionMailer

A really easy way to send an email using your company default settings. Integrate this with API call results to make notifications a breeze!

var mailer = new ScriptableFunctionMailer();

mailer.CompanyId = companyId; // companyId from Signature
mailer.Subject = "Email Test Subject";
mailer.Body = "Email Test Body";
mailer.Recipients = "[email protected]";
mailer.HasBranding = false;
mailer.Send();ScriptableFunctionMailer


ScriptableFunctionJsonToHtml

This really useful function converts a JSON response to an HTML table, saving hours of work when parsing JSON responses.

var scriptableFunctionJsonToHtml = new ScriptableFunctionJsonToHtml(); 
return scriptableFunctionJsonToHtml.ToTable(JSON.stringify(item));


ScriptableFunctionSlackClient

Post to Slack

var client = new ScriptableFunctionSlackClient(webHookUrl, "#channel", "user");
client.Say("Hi");

Did this answer your question?