JS SDK examples

Examples of handling arrays

Example 1. Intersection of arrays.

In this example we are going to match candidates (structure Cand) with job offers (structure Jobs) taking into account intersection in skills (arrays like finance,management,programming). Skills of the candidate are stored in cand_skills, required skills of the job are stored in job_skills. Result of matching is saved to Job object, field candidate_ids.

Here we use the following functions:

Content in JS SDK step:

// Scenario processes objects from Jobs
​
DirectualEngine.addEventListener(AppEvents.START, function(context){
var candidates = $D.getValueFromTemplate("{{candidates_ids}}")
var skills = $D.getValueFromTemplate("{{job_skills}}")
var id = $D.getValueFromTemplate("{{id}}")
​
var matchCand = []
if (candidates) {
candidates.split(",").forEach(function(cand) {
var candSkills = $D.store.get("Cand", cand, {fields: ["cand_skills"]});
if ($D.arrayContainsAny(candSkills, functions)) {
matchCand = $D.concat(matchCand,cand)
}
})
}
$D.store.save("Jobs", {"id": id, "candidate_ids": matchCand }, false)
return true;
});

Example 2. Composing a JSON with custom property names

​JSON step is great, but it does not support custom property names. Here is how to cope that.

For example we have structures Authors and Books and I want to compose JSON like this:

{
"name": "Leo Tolstoy",
"book1": {
"id": "book1",
"title": "War and Peace"
},
"book2": {
"id": "book2",
"title": "Anna Karenina"
}
}

We can do that with the following JS SDK code:

DirectualEngine.addEventListener(AppEvents.START, function(context){
var id = $D.eval('{{id}}')
var array = $D.eval('{{book_ids}}').split(',')
var newObject = {}
newObject.name = $D.eval('{{name}}')
array && array.map(function(book) {
newObject[book] = {}
var bookObject = $D.store.get("Books", book, {fields: ["Title", "Year"]});
for (var field in bookObject) {
newObject[book][field] = bookObject[field]
}
})
//saving result object
$D.store.save("WebUser", {"id": id, "json": JSON.stringify(newObject) }, false)
return true
});