IBM Worklight - How to parse adapter response? - javascript

This is my stored procedure:
CREATE PROCEDURE PROC()
BEGIN
SELECT * FROM TABLENAME;
END//
This is my unction to call stored procedure using SQL adapter:
function callStored() {
return WL.Server.invokeSQLStoredProcedure({
procedure : "proc",
parameters : []
});
}
This is the invocationResult:
{
"isSuccessful": true,
"resultSet": [
{
"name": "a",
"pass": "123",
"time_stamp": "2014-04-07T10:13:17.000Z"
},
{
"name": "chetan",
"pass": "123456",
"time_stamp": "2014-04-07T10:13:34.000Z"
},
{
"name": "dileep",
"pass": "456321",
"time_stamp": "2014-04-07T10:13:54.000Z"
},
{
"name": "bnc",
"pass": "654321",
"time_stamp": "2014-04-07T10:19:37.000Z"
}
]
}
I need to parse this and display or alert the values of name, pass and time_stamp.
How do I accomplish this?

In your application JavaScript (common\js\main.js), you can have something like the following. In the below code an alert will be displayed with the values of the name key from the resultSet.
You can also take a look here: use resultset returned by WL.Server.invokeSQLStatement within sql adapter procedure
function wlCommonInit() {
invokeAdapter();
}
function invokeAdapter() {
var invocationData = {
adapter: "your-adapter-name",
procedure: "callStored",
parameters: []
};
WL.Client.invokeProcedure (invocationData, {
onSuccess: invocationSuccess,
onFailure: invocationFailure}
);
}
function invocationSuccess(response) {
var i,
resultSet = response.invocationResult.resultSet;
namesArray = [];
for (i = 0; i < resultSet.length; i++) {
namesArray[i] = resultSet[i].name;
}
alert (JSON.stringify(namesArray));
}
function invocationFailure(response) {
alert (response);
}
You have already asked this here: ibm worklight stored procedure
Why did you not follow through the documentation and learned how to write the above?
Please read the documentation!

Please read the "Invoking adapter procedures from client applications" and its Exercise and code sample in the Getting started with IBM Worklight page.
function wlCommonInit(){
getUsersInfo();
}
function getUsersInfo(){
var invocationData = {
adapter : 'YOUR_ADAPTER',
procedure : 'YOUR_PROCEDURE',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : getUsersInfoSuccess,
onFailure : getUsersInfoFailure
});
}
function getUsersInfoSuccess(result){
if (result.invocationResult.Items.length > 0) {
displayUsersInfo(result.invocationResult.Items);
} else {
getUsersInfoFailure();
}
}
function getUsersInfoFailure(result){
alert("Cannot retrieve users info");
}
function displayUsersInfo(items){
var i = 0, usersInfo = '';
for (i = 0; i < items.length; i++) {
usersInfo += ' name: ' + items[i].name;
usersInfo += ' pass: ' + items[i].pass;
usersInfo += ' time_stamp: ' + items[i].time_stamp;
}
alert(usersInfo);
}

Related

Convert the simple fetch API code to ".then" notation code

How can I covert following code into .then notation. I wanted to strictly use ".then" notation. That is what I observed with my system.
I raised one question with similar kind of request however, I got the code using async/await. Rather than asking the new requirement over the same thread I initiated this new thread.
Apology for inconvenience. I should have posted this it in first thread itself. Kindly help.
var obj = [{"Id":"10101","descr":"server1.com"},{"Id":"10102","descr":"server2.com"},{"Id":"10103","descr":"server3.com"},{"Id":"10104","descr":"server4.com"},{"Id":"10105","descr":"server5.com"},{"Id":"10106","descr":"server6.com"},{"Id":"10107","descr":"server7.com"}];
var temp = [];
for (var i = 0; i < obj.length; i++){
var id = obj[i].Id;
let response = await fetch('https://abced.com/api/'+id+'/value', {method : "GET", headers: {"Authorization": "xyz"}});
var data = await response.json();
var stats = data.status;
if (stat != "OK")
{
temp.push({Id:obj[i].Id, descr:obj[i].descr, value:"ERROR"})
}
}
console.log(temp);
My expected output is, (values of Id and descr will depends on "if statement" in the code)
[{"Id": "10101","descr": "server1.com","status": "ERROR"},
{"Id": "10103","descr": "server3.com","status": "ERROR"},
{"Id": "10104","descr": "server4.com","status": "ERROR"}]
I tried following but in my system compiler says, "Function declared within loops referencing an outer scope variable mat lead to confusing semantics (Id, descr)"
function fetchMock(url) {
let id = url.split('/')[4];
if ([10101, 10103, 10104].includes(+id)) {
return Promise.resolve({
json() {
return Promise.resolve({
status: 'BAD'
});
}
});
} else {
return Promise.resolve({
json() {
return Promise.resolve({
status: 'OK'
});
}
});
}
}
var obj = [{
"Id": "10101",
"descr": "server1.com"
},
{
"Id": "10102",
"descr": "server2.com"
},
{
"Id": "10103",
"descr": "server3.com"
},
{
"Id": "10104",
"descr": "server4.com"
},
{
"Id": "10105",
"descr": "server5.com"
},
{
"Id": "10106",
"descr": "server6.com"
},
{
"Id": "10107",
"descr": "server7.com"
}
];
function getResults() {
const results = [];
for (let {
Id,
descr
} of obj) {
fetchMock('https://abced.com/api/' + Id + '/value', {
method: "GET",
headers: {
"Authorization": "xyz"
}
}).then(res => res.json()).then(function(data) {
if (data.status !== 'OK') {
results.push({
Id,
descr,
value: 'ERROR'
});
}
});
}
return results;
}
function test() {
const results = getResults();
return results;
}
test();

Multiple paramater based routes for an API Endoint in an Azure Function

I have a simple Function App in Azure that returns data in JSON.
https://myurl.com/api/symbolcountry/{id}?
It takes in a single id for a parameter. It works well.
However I'd like to parameterize part of the url
https://myurl.com/api/{endpoint}/{id}?
I've never messed around with javascript and am going a bit nuts trying to figure this one out.
function.json file:
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get"
],
"route": "symbolcountry/{id}"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
index.js file:
module.exports = function (context, req) {
const method = req.method.toLowerCase();
var payload = null;
var entity = "";
switch(method) {
case "get":
if (req.params.id) {
entity = "symbolcountry"
payload = { "SymbolID": req.params.id};
}
else {
entity = "symbols"
}
break;
}
}
Tried adding paramters in function.json to no avail.
If you want to access the params passed in the URL instead of params use the key work query
Your code will look like this:
module.exports = function (context, req) {
const metthod = req.method.toLowerCase();
var payload = null;
var entity = "";
switch(metthod)
{
case "get" : if(req.query.id)
{
entity="symbolcountry";
payload = {
"SymbolId":req.query.id
}
}
break;
}
context.res = {
body = payload
}
The above code will return the payload
output :
If you want to parameters through routing, you can refer this article by JOE GATT

SQL Tedious Loop through object of array and execute insert statement function error Request is not a constructor

I'm new to Js, and would appreciate some help.
Currently, via tedious js, I've written a sql function that passes an insert statement that loops through an array of objects and inserts each property in each object in array to SQL.
To do this, I've written a loop to iterate through the array, and insert each property as a new entry into sql.
However, when i try to execute the function after the connect, the function returns error Request is not a constructor
Here is the full code below. Is there some scope issue here, or am I not correctly handling the tedious js events properly or is there some sort of issue with my for loop?
var jsonArray = [];
let jsonobj = {
test: "1",
test2: "2"
}
let jsonobj1 = {
test: "23",
test2: "54"
}
jsonArray.push(jsonobj)
jsonArray.push(jsonobj1)
jsonArray.push(jsonobj)
var config = {
server: '123', //update me
authentication: {
type: 'default',
options: {
userName: '123', //update me
password: '1234' //update me
}
},
options: {
// If you are on Microsoft Azure, you need encryption:
//encrypt: true,
requestTimeout: 30 * 1000,
trustServerCertificate: true,
database: 'db', //update me
rowCollectionOnRequestCompletion: true,
rowCollectionOnDone: true
}
};
var connection = new Connection(config);
connection.on('debug', function(err) { console.log('debug:', err);})
connection.on('connect', function(err) {
});
for (var i = 0; i < jsonArray.length; i++){
var sql = `insert into store (storekey,ip,port) values ( \'${jsonArray[i].test2}\' , '2' , '6');`
executeStatement1(sql)
}
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement1(sql) {
request = new Request(sql, function(err) {
if (err) {
console.log(err);}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(" success " + column.value);
}
});
});
connection.execSql(request);
}

How to verify the particular value of the DB node of firebase database

I have a JSON structure as
{
"engagedUsers": {
"qwe": {
"agent_availability": true,
"conv_id": "parthengineer_qwe",
"emailId": "qwe#gmail.com",
"login_time": 1512644440,
"name": "qwe",
"uid": "adasfklsfjdskldgsgjgjkl"
},
"tt": {
"agent_availability": true,
"conv_id": "genesis_tt",
"emailId": "tt#gmail.com",
"login_time": 1512644440,
"name": "tt",
"uid": "adasfklsfjdskldgsgjgjkl"
}
}
}
I want to verify if the conv_id child is equal to parthengineer_qwe. I tried the below code but cannot got through it:
this.engagedRef = firebase.database().ref('engagedUsers');
this.engagedRef.orderByValue().once('value', function (snapshot) {
snapshot.forEach(function (data) {
// console.log("snapShot:" + data.child('conv_id').val());
if ((data.child('conv_id').val() == 'parthengineerqwe') && (existEngageduser !== 1)) {
existEngageduser = 1
// console.log("under haschild:" + existEngageduser);
}
if (existEngageduser == 1) {
isEngaged = true
// sessionStorage.isEngaged = isEngaged;
}
// console.log("isEngaged:" + isEngaged);
})
return isEngaged;
});
Please suggest a better way to achieve this as I know I am not going right way, I expect isEngaged variable as true
I'm still not sure what you want but why not have an external function to do it?
snapshot.forEach(function (data) {
if (isEngaged(data.val())) {
console.log(data.key, ' is engaged');
}
}
function isEngaged(userData) {
return (userData.conv_id === 'parthengineer_qwe') || false;
}

How to update relation details in Neo4j using cypher query?

data= {
"id": 1,
"name": "samuel",
"Manager": [
{
"id": "",
"name": "manager1",
"approvers": [325,134],
}
]
}
FOR this data object , we did the add function using a similar given cypher query in Neo4j
query = "CREATE CONSTRAINT ON (users:user) ASSERT users.name IS UNIQUE";
return cypher(
{
"query": query
}
).then(function () {
query = "CREATE (user:user{ name:"samuel "})
"RETURN user";
action = "create";
return cypher(
{
"query": query,
});
}).then(function (data) {
userId = data[0].user._id;
return Promise.each(data.manager, function (entry) {
query = "MATCH (user: user) WHERE id(user) = " + userId + " " +
" OPTIONAL MATCH (managerApprovers:user) WHERE id(managerApprovers) IN [325,134] " +
"CREATE (manager: managernode {name: "manager1"})<-[:HAS_MANAGER]-(user) " +
"FOREACH (a IN CASE WHEN managerApprovers IS NOT NULL THEN [managerApprovers] ELSE [] END | " +
"CREATE (managerApprovers)<-[:HAS_MANAGE_APPROVER]-(managernode)) RETURN user,managernode";
return cypher(
{
"query": query,
}).then(function (data) {
{
res.action = action;
res.result = data;
return res;
});
}
if we want to update the user name along with updating the manager details and the relation HAS_MANAGE_APPROVER,HAS_MANAGER how is it performed in Neo4j
You have to MATCH the relation, store it in a variable and then SET the property you want:
Match (a:firstNode)-[relation:MY_RELATIONSHIP]->(b:secondNode)
SET relation.variable="Foo"
Keep in mind that using neo4j internal ID is not recommended, see Should we use the Neo4J internal id?

Categories

Resources