node js recursive concept - node.js

I am new to Node.js technology and facing some issues in recursive concept.
I have a main.js which contains list of username and a soap method call Soap.js contains soap method which will fetch email id from username.
------------- Main.js ----------------
'use strict'
var emailService = require('./emailService .js').emailService ;
var emailService1 = new emailService ();
var emailList = [];
var psList = ['1062','10465','10664','10681'];
emailService1.helpdeskEmailService(psList, 'abcabc', 'abcabc', function(err,result) {
console.log('in service -------------------------');
if (err) {
console.log("Error while api call :: " +err);
} else {
console.log("response from soap service - " + result);
}
});
console.log('my email list' +result);
------------- SoapService.js ----------------
'use strict'
var c_instancename = '';
var soap = require('soap');
var l_args;
var c_url = "http://airinmsbmcarmt.lntinfotech.com/arsys/WSDL/public/172.21.103.136/zlandt:FetchEmailID";
class emailService {
constructor(p_instanceName) {
c_instancename = p_instanceName;
}
helpdeskEmailService (ps_number,p_username,p_password,p_callback) {
var l_header = {
'authentication': '',
'locale': '',
'timeZone': '',
'AuthenticationInfo': {
'userName': p_username,
'password': p_password
}
}
soap.createClient(c_url, function(err, client) {
//var soapheader = l_header;
client.addSoapHeader(l_header);
var l_args = {LoginID:ps_number};
client.EmailID(l_args, function(err, result) {
if(err) {
console.log('error page');
} else {
console.log('my resultttttttt in soap...');
p_callback(err,result);
}
});
});
}
}
module.exports.emailService = emailService;
In this case, I'm getting late response from soap service.
Can I have sync call for webservice because I am getting NULL values for emailList.
I have a main.js which contains list of username and a soap method call.
Soap.js contains soap method which will fetch email id from username.

You can return a promise from your service and if you're using Node 8.0+ you can also make the call synchronous. If not at least it makes it easier to deal with asynchronous call.
helpdeskEmailService (ps_number,p_username,p_password) {
var l_header = {
'authentication': '',
'locale': '',
'timeZone': '',
'AuthenticationInfo': {
'userName': p_username,
'password': p_password
}
}
return new Promise (function (resolve, reject) {
soap.createClient(c_url, function(err, client) {
//var soapheader = l_header;
client.addSoapHeader(l_header);
var l_args = {LoginID:ps_number};
client.EmailID(l_args, function(err, result) {
if(err) {
console.log('error page');
reject(err);
} else {
console.log('my resultttttttt in soap...');
resolve(result);
}
});
});
}
}
// You can then call like this
var promise = emailService1.helpdeskEmailService(psList, 'abcabc', 'abcabc');
promise.then((result) => {
console.log("response from soap service - " + result);
}).catch ( (err) => {
console.log("Error while api call :: " +err);
});
You can also use await to make this synchronous (depending on the version of Node you're using):
async function waitForresult() {
try
{
const result = await emailService1.helpdeskEmailService(psList, 'abcabc','abcabc');
console.log(result);
} catch (e) {
console.log('Error occurred: ' + e);
}
};
waitForresult();

Related

AdonisJS unable to return response within a function (SAP HANA)

I am using SAP HANA CLIENT for NodeJS in my AdonisJS project. I am unable to return the response as json from the the function that connects to the database. Here is the code
The controller method validateInvoice is first called
async validateInvoice({request, response}) {
const req = request.all()
const inv_num = req.invoice_num;
const data = await this.fetchInvStatus(inv_num);
return response.json({success: true, data: data});
}
This in turn calls the fetchInvStatus method which actually connects to HANA DB
var conn = hana.createConnection();
var conn_params = {
serverNode: '127.0.0.1:30015',
uid: 'CUST_USER_ROLE_ADMIN',
pwd: 'Welcome#1234',
database: 'DED'
};
conn.connect(conn_params, (err) => {
if(err) {
return err;
}
conn.exec("Select * FROM SAPDED.YACSF_RRHD where INVOICE_NUMBER = ?", ['BOMT000005'], (err, result) => {
if (err) {
return err;
}
console.log(result);
return result;
})
});
In the console I'm able to see the result but this result is not being passed to the validateInvoice method so that the API could return the response.
The line in the first method response.json() is executed even before the data from DB is returned. How can I overcome this problem? I've tried adding return statement to conn.connect and conn.exec but nothing helps!
You have to return promise in the fetchInvStatus method.
function fetchInvStatus() {
return new Promise(resolve, reject) {
var conn = hana.createConnection();
var conn_params = {
serverNode: '127.0.0.1:30015',
uid: 'CUST_USER_ROLE_ADMIN',
pwd: 'Welcome#1234',
database: 'DED'
};
conn.connect(conn_params, (err) => {
if(err) {
reject(err);
}
conn.exec("Select * FROM SAPDED.YACSF_RRHD where INVOICE_NUMBER = ?", ['BOMT000005'], (err, result) => {
if (err) {
reject(err);
}
console.log(result);
resolve(result);
})
});
}
}

Botpress - how to bring database values into the chat window?

I'm trying to build a chatbot using Botpress. I'm a beginner, looking for your help. One of the requirements is to query database to answer questions. This is what I have tried so far:
dbconnect.js
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');
var db = function dbCall(sql, values) {
return new Promise(function(resolve, reject){
oracledb.getConnection(
{
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
},
function(err, connection) {
if (err) {
reject(err);
return;
}
connection.execute(
sql,
values,
{
maxRows: 1
},
function(err, result) {
if (err) {
console.error(err.message);
return;
}
resolve(result);
doRelease(connection);
}
);
});
});
}
// Note: connections should always be released when not needed
function doRelease(connection) {
connection.close(
function (err) {
if (err) {
console.error(err.message);
}
});
}
module.exports = db;
select.js
var dbConnect = require('../oracledb/dbconnect');
dbConnect('select code from table1' +
' where id=:id', {id:'value1'}).then(function (response) {
console.info(response.rows);
}).catch(function(error) {
console.info(error);
});
everything above works great, if I run select.js. How could I bring the response into the botpress chat window? I tried placing the select.js code in index.js event.reply, it doesn't work.
Thanks,
Babu.
I have resolved this by using the promise directly in the action.
return dbConnect('<SQL here>=:id', { id: Id })
.then(function(response) {
var res = response.rows
console.info(res);
const newState = { ...state, status: res}
return newState
})
.catch(function(error) {
console.info(error)
})
Note that response has the resultset.

Async await issue in nodejs

I am trying to send messages to mobile numbers using message bird API, i have completed the coding part but its not sending the messages, even i can see i have sent messages and being delivered in my message bird profile. I came to know that this issue can be due to not using async and await. Here is my code,
api.get('/sendmessage', function (req, res) {
var id = req.headers.authorization;
if (req.session.id) {
var userid = req.session.user[0].id;
var username = userInfo.find({ id: userid }, function (err, user) {
if (err) { res.send("New Error: " + err); }
else {
if (!_.isEmpty(user)) {
var contact = user[0].contact;
var messagebird = require('messagebird')('ACCESS_KEY_API'); // Api for testing
var params = {
'originator': 'MessageBird',
'recipients': [
contact
],
'body': 'Hello, world!'
};
messagebird.messages.create(params, function (err, response) {
if (err) {
return console.log("Error sent to Console: " + err);
}
else {
console.log(response);
return res.send(response);
}
});
}
else {
res.send("No Results");
}
}
});
}
});

async.eachSeries runs only once with async.waterfall inside for each iteration

I am new to async library. I have used async.eachSeries and async.waterfall for each iteration. I see, the async.waterfall runs only once.
Here is my code :
var fs = require('fs'),
async = require('async'),
Client = require('node-rest-client').Client;
// REST API Call and output in jsonOutput.results
console.log(jsonOutput.results.length); // jsonOutput.results has 124 records.
async.eachSeries(jsonOutput.results, function(account, callback) {
var dataObject = {};
dataObject.updatetime = new Date();
var setAccountInfoURL = ""; // Data Update REST API Request
async.waterfall([
function setAccountInfo(updateCallback) {
// client.get(setAccountInfoURL, function (data, response) {
// var jsonOutput = JSON.parse(data.toString('utf8'));
updateCallback(null, "output", account)
// });
},
function saveAccountInfo(jsonOutput, account, updateCallback) {
var debuglog = JSON.stringify(account) + "\n" + jsonOutput;
fs.appendFile("debuginfo.json", debuglog + "\n", function (err) {
if(err) {
console.log(err);
}
console.log("JSON saved to " + "debuginfo.json");
updateCallback(null);
});
}
],function asyncComplete(err) {
if (err) {
console.warn('Error setting account info.', err);
}
console.log('async completed');
});
}, function(err){
if (err) {
console.log('error in loop');
}
console.log('loop completed');
});
Output:
124
JSON saved to debuginfo.json
async completed
Any help is really appreciated.
I found my mistake. I missed calling the callback after each iteration just after async is completed.
var fs = require('fs'),
async = require('async'),
Client = require('node-rest-client').Client;
// REST API Call and output in jsonOutput.results
console.log(jsonOutput.results.length); // jsonOutput.results has 124 records.
async.eachSeries(jsonOutput.results, function(account, callback) {
var dataObject = {};
dataObject.updatetime = new Date();
var setAccountInfoURL = ""; // Data Update REST API Request
async.waterfall([
function setAccountInfo(updateCallback) {
// client.get(setAccountInfoURL, function (data, response) {
// var jsonOutput = JSON.parse(data.toString('utf8'));
updateCallback(null, "output", account)
// });
},
function saveAccountInfo(jsonOutput, account, updateCallback) {
var debuglog = JSON.stringify(account) + "\n" + jsonOutput;
fs.appendFile("debuginfo.json", debuglog + "\n", function (err) {
if(err) {
console.log(err);
}
console.log("JSON saved to " + "debuginfo.json");
updateCallback(null);
});
}
],function asyncComplete(err) {
if (err) {
console.warn('Error setting account info.', err);
}
console.log('async completed');
callback(null); // this is the change.
});
}, function(err){
if (err) {
console.log('error in loop');
}
console.log('loop completed');
});

sending data from Javascript to save in mongoDB through nodejs

I am trying to parse an object from a javascript (a blog post head and body) through a node.js server and on to save it in the mongoDB.
this is the parsing code:
function saveState( event ) {
var url = '';
var postTitle = headerField.innerHTML;
var article = contentField.innerHTML;
var post = {
title: postTitle,
article: article
};
var postID = document.querySelector('.save').getAttribute('id');
if(postID != "new"){
url += "?id=" + postID
}
var request = new XMLHttpRequest();
request.open("POST", "draft" + url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(post);
}
this is sent to this node server handler:
app.post('/draft', routes.saveDraft);
exports.saveDraft = function(req, res){
var id = url.parse(req.url, true).query.id;
var post = db.getPostByID(id);
if(id){
console.log('post id' + id);
db.savePost(id, req.body.head, req.body.article);
}
else{
db.newPost(req.body.head, req.body.article);
}
res.render('editDraft.hbs', post); //send the selected post
};
and then, sent to one of these DB functions:
exports.newPost = function (postTitle, article) {
new postCatalog({title:postTitle,
_id:1,
author:'temp',
AuthorID:2,
date:'2/3/12',
inShort:article.substring(0,100),
content:article ,
published:false
}).save(function (err, login) {
if (err) {
return console.log('error');
}
else {
console.log('Article saved');
}
});
}
exports.savePost = function (id, postTitle, article) {
postCatalog.find({_id: id}).save(function (err, login) {
if (err) {
return console.log('error');
}
else {
console.log('Draft saved');
}
});
}
now, I just can't get this to work..
I am new to node and I could really use your help!
thanks
EDITED:
the parameters being sent to the DB saving functions were not written properly.
but i'm still stuck in the same place, where the data is being sent but not saved correctly. I think there's something wrong with my getPostByID function but I can't figure it out:
exports.getPostByID =function (id) {
var post = postCatalog.find({_id: id}, function(err, post){
if(err) {
return handleError(err);
}
else{
if(post > 0){
post = post[0];
}
return post;
}
});
return post;
}
I am using express (including bodyparser) and mongoose. view engine is hbs.
thanks again.
You have to write it the asynchronous way, e.g. your getPostByID:
exports.getPostByID = function (id, callback) {
postCatalog.find({_id: id}, function(err, post) {
if (err) {
callback(err);
}
else if (post && post.length > 0) {
callback(null, post[0]);
}
else {
callback(null, null); // no record found
}
});
};
And this is true for your whole code. It's totally different and the way you tried it will never work under Node.js.
BTW there is a mongo-driver method findOne which is better suited in this special case but I didn't want to change your code too much.

Resources