External Helper libraries

A summary of external helper libraries available in template

There are many additional external helper functions available in the scope of the template body. Let’s have a short look at them.

Chancejs

Chancejs is a random content generation library which is quite useful to generate data. E.g. to generate a random street addresss

state['street'] = chance.address();
state['city'] = chance.city();
state['zip'] = chance.zip();
return JSON.stringify(state);

And voila, you have a perfectly looking fake street address.

Momentjs

Momentjs is another super useful library, especially to manipulate time. In below example, we will calculate the elapsed time since the simulation started (iteration 0)

{
if ( state['start'] === undefined ) {
state['start'] = moment.now();
}
state['elapsed'] = moment(state['start']).fromNow();
return JSON.stringify(state);
}

UnderscoreJS

UnderscoreJS is another popular library which is a must have for serious javascript programmer. Here is an example of filtering even values in an array

{
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){
return num % 2 == 0; }
);
return JSON.stringify(evens);
}

deasync JS

Deasync could be used to create synchronous behavior out of async or callback based function. Though async functions should be used as much as possible, in some cases, deasync could make life easier. E.g. in the code snippet below, we are waiting for the callback function to finish while calling setTimeout() async function.

{
var ret;
setTimeout(function(){
ret = "hello";
},3000);
while(ret === undefined) {
deasync.sleep(100);
}
}

JSON web tokens

JSON web tokens are gaining popularity as an authorization mechanism. IOTIFY template now supports creating JWT by integrating jsonwebtoken NPM library JSON Web Token

{
// You could use {{state.token}} in the HTTP auth header
// The function is evaluated before the headers.
state.token = jwt.sign({ foo: 'bar' }, 'shhhhh');
}

Note that use of deasync function slows down the excution significantly.

Native builtin object

There are several built in module available in the function body. Math is one of them which is quite useful for arithmetic.