lslapp-example
v1.3.0
Published
This package is the base template to get started with LeadSquared Apps - Lapps. All the features supported with the online platform are mocked so that offline development can be done with utmost ease
Downloads
5
Readme
lslapp
This package is the base template to get started with LeadSquared Apps - Lapps. All the features supported with the online platform are mocked so that offline development can be done with utmost ease.
Installation
Note: this package runs locally on node version >
12.x
. It is advisable to make the target node version specifically to12.x
, as deployment is done on the same version.
You must install lslapp globally
$ npm install -g lslapp
Note to linux users You must not install the package with sudo. To change the permission to the current user just run
$ sudo chown -R $(whoami) ~/.npm
Usage
There are some basic commands with lslapp -
Initialize a new Lapp
In your project folder, enter the following command -
$ lslapp init
It will prompt for the Lapp name as below. Let's give it a name say "first-lapp"
$ Your Lapp name: first-lapp
A Lapp template is generated, Navigate to main.js
and write your code.
Run a Lapp
Navigate inside the directory of the Lapp and enter the following command -
$ cd first-lapp
Enter the following command to run and test your Lapp locally -
$ lslapp run
The Lapp executes locally and returns a response.
Packaging a Lapp for deployment
Ensure you are inside your created Lapp's root folder. Run the following command to prepare a deployable zip file in deliverables
folder:
$ lslapp pack
Configuring Tenant Profile
You can create multiple tenant profile using configure command
$ lslapp configure
It will prompt for the below values:
- Profile name - We suggest to give name as "orgcode-accesslevel"
- OrgCode - LeadSquared's organization code
- Region - Valid values (1, 11, 21, 31) 1 for SGP, 11 for US, 21 for MUM, 31 for IR
- Token - Generated from LeadSquared's Lapps admin portal. If needed contact the support team and get this token.
Once the profile is created, you can use this profile for save and publish commands
You can also simply run lslapp, it will prompt all available commands
$ lslapp
Creating and uploading a Lapp code for deployment
Make sure you pass the command line parameters -orgcode -region -token . You may also pass these parameters as -o,-r and -t.
eg. lslapp save -orgcode 1234 -region 1 -token asdfghijkl1234
eg. lslapp save -o 1234 -r 1 -t asdfghijkl1234
Alternatively, if you have configured profile use -profile
eg. lslapp save -profile mytenant1234
eg. lslapp save -p mytenant1234
Note:
- If the Lapp Id doesn't exist in the
config.json
file, the command creates a Lapp and uploads the code. - If the Lapp Id exist in the
config.json
file, It packs and uploads the code to the Lapp
$ lslapp save -profile <profilename>
Deploy or Publish a Lapp
The following command publishes the Lapp to Test environment.
Make sure you pass the command line parameters -orgcode -region -token or if you have configured profile use -profile
eg. lslapp publish -profile mytenant1234
eg. lslapp publish -p mytenant1234
eg. lslapp publish -orgcode 1234 -region 1 -token asdfghijkl1234
eg. lslapp publish -o 1234 -r 1 -t asdfghijkl1234
$ lslapp publish -profile <profilename>
Note: Only Admin and Developer-Publisher can publish a Lapp to test environment.
Publish a Lapp to Live Environment
If you want to publish to Live Environment, use the below command:
$ lslapp publish -profile <profilename> -live true
Note: Only Admin can publish a Lapp to live environment.
Documentation
setting.json
If you wish to request LeadSqured Rest APIs, you might want to configure the setting.json
file for base API URL, access key and secret key; that is available in your LeadSquared admin account.
For e.g. you setting.json
file can contain
{
"LS_API_BASE_URL": {
"Test": "<your-api-url>",
"Live": ""
},
"LS_ACCESS_KEY": {
"Test": "<test-env-access-key>",
"Live": ""
},
"LS_SECRET_KEY": {
"Test": "<test-env-secret-key>",
"Live": ""
}
}
Alternatively, you can always hard code your credentials in the Rest API request, but that's not advisable. Storing your key-value pairs in setting.json
actually gets encrypted when you upload your packaged zip file to your LeadSquared account.
main.js
The main.js
is the entry point for your implementation. Please read the inline code and comments to understand the basic rules. In short, it is very similar to online Lapp editor code.
Below are the notable points:
The main.js
has a main() function which accepts 3 parameters. The signature is as follows:
main(queryString, body, callback);
At actual runtime, these values are supplied from your Lapp API URL request. For offline development and testing, you can mock queryString
and body
passed to the main() in the event.json
file
queryString
If you pass the following query string to the API:
<APIURL>?firstName=john&lastName=doe
They are converted to json object and can be accessed
let firstName = queryString.firstName;
let lastName = queryString.lastName;
body
if you pass the following body –
{"FirstName": "John", "LastName":"Doe"}
or any other content-type, say xml, they will be converted to json object as main function parameter and can be hence accessed as:
let firstName = body.FirstName;
let lastName = body.LastName;
callback
is the mandatory funtional parameter, that you need to call inside main
function, in order to return the reponse to the API caller.
It has the following signature –
callback(Error error, Object result) { }
error
is used to provide the results of the failed Lapp execution, for example,callback(error, null)
. When a Lapp function succeeds, you should pass first parameter as null, for examplecallback(null, data)
result
is used to provide the result of a successful Lapp execution. The result provided must be JSON.stringify compatible. If an error is provided, this parameter should be null.
Please note that calling callback
function is mandatory, without which you might not get expected response from Lapp and Lapp logs
Lapp Response
Response of Lapp is always formatter in the following format.
{ "statusCode" : 200 , "message" : <your_response>}
Here are some sample values you can return using the callback function.
****************** string ********************************
{
"statusCode": 200,
"message": "hello"
}
****************** simple json ********************************
{
"statusCode": 200,
"message": {
"id": "123"
}
}
****************** json array ********************************
{
"statusCode": 200,
"message": [{
"id": 1
},
{
"id": 3,
"name": "John Doe"
}]
}
****************** complex json ********************************
{
"statusCode": 200,
"message": [{
"id": 1
},
{
"id": 3,
"details": {
"firstName": "John",
"LastName": "Doe "
}
}]
}
Logging
We can log data in the following way:
let messageInString = "string message";
let varOject = { message: "Lapp rocks!" };
//log an info, just message
ls.log.Info(messageInString);
//log message with object
ls.log.Info(messageInString, varObject);
//To log an error, assuming errorObject
ls.log.Error("Error", errorObject);
General guidelines to debug and catch error
- Always write your functions in
try/catch
block. From inner fucntion, throw the Error. From main function respond with callback(error,null). If you follow this pattern, it is almost certain that you will be provided with the actual error causing statement or behaviour at runtime - Log important pieces of you code flow gracefully.
Example of an an LeadSquared API call with async-await
const apiHelper = require("./ls-api-helper"); //this is an internal wrapper to formulate request call's ```options``` parameter, specifically for LeadSquared APIs
function main(queryString, body, callback) {
try {
let run = async () => {
newLead = await createLead(body);
ls.log.Info("Lead Created:", newLead);
};
run();
} catch (error) {
ls.log.Error("Error", error);
}
}
/**
* This is an example of how to make an LeadSquared API call to create a new Lead
* @param {Object} body
*/
function createLead(body) {
// assumption that body contains email, firstName and lastName from request
let leadParams = [
{ Attribute: "EmailAddress", Value: body.EmailAddress },
{ Attribute: "FirstName", Value: body.FirstName },
{ Attribute: "LastName", Value: body.LastName },
];
// returns a Promise so that await waits for the execution
return new Promise((resolve, reject) => {
let options = apiHelper.getOptions("LeadManagement.svc/Lead.Create", {}, leadParams);
// making post request call
request.post(options, (error, response, body) => {
if (error) {
ls.log.Error("Error", error);
reject(error);
} else {
if (response.statusCode == 200) {
ls.log.Info("Success", body);
resolve(body);
} else {
reject(new Error(JSON.stringify(body)));
}
}
});
});
}
Genarating PDF from html
refer to sample code below:
function main(queryString, body, callback) {
let html = "<h1>Hello</h1>";
// first param is html as string
// second param is options as described in html-pdf @ https://www.npmjs.com/package/html-pdf. Please note that this is only to mock the pdf implementation. This package should not be used in any way in your code
ls.lib.generatePDFV2(html, {}, (err, data) => {
if (err) callback(err, data);
else callback(null, data);
});
}
//default 2nd param values are as follows:
let options = {
format: "A4",
orientation: "portrait",
border: ".50in", //its not border but leaves a margin around 4 sides
type: "pdf",
renderDelay: 500, // so that scripts can execute
};
Node packages
Following are the nodejs packages that can be used in the code
Important - Lapp does not allow externally deployed node.js packages due to security reasons
Do not touch
Following files have been used to mock the exact implementation of Lapp.
- index.js
- dbstore.js
- helper.js
- lib.js
- pdf-lib.js
- log.js
- serverless.yml
- mssqlproxy.js
- mysqlproxy.js
- securerequest.js
Do not alter these files in any manner, else it will result un-wanted behaviour of Lapp.
Do not create a file by name setting.js
at root folder of Lapp.
File ls-api-helper
can be altered as per your own need