Below is the code I tried:
fetchUserDetails: function () {
var url = 'http://ldniguiapp02.eur.ad.tullib.com/matchbox-forwarddeal/services/RefDataWebServices?wsdl';
var args = {'args0':
{
'mnemonic':'ttan',
'postingId':'75655',
'customerId':'180816',
'organisation':{
'customerId':'180816',
'firmName':'POLITICAL.GROUP'
},
'userType':'TRADER'
}};
var defered = q.defer();
soap.createClient(url, CreateClient);
function CreateClient(err, client) {
client.getUserDetails(args, function (err, result) {
if (err) {
defered.reject(err);
}else{
defered.resolve(result);
}
console.log(result);
});
}
return defered.promise;
}
and the equivalent SOAP request from SOAP UI looks something like this:
How can I format args json so as to get expected result?
You should transform your json in xml
Here you can do this online (to check/verify/test) http://convertjson.com/json-to-xml.htm
And off course there is an npm module that does just this:
https://www.npmjs.com/package/jsontoxml
...
var jsonxml = require('jsontoxml');
var xmlArgs = jsonxml(args);
...
client.getUserDetails(xmlArgs, function (err, result) {
...
})
...
I hope this helps
Related
I want to get data from Redis session with nodejs - but i can't get the inner values of the objects....
this is a simple router
router.get('/page-user', function (req, res) {
console.log(redis_model.prototype.getAll());
})
and here is the model
redis_model.prototype.getAll = function () {
client.keys('*', function (err, keys) {
if (err) return console.log(err);
for(var i = 0, len = keys.length; i < len; i++) {
console.log(keys[i]);
}
});
};
So i'm getting
users
id:users
session:php:cf5myWFkDNEPwiRLpi6M1P6LqX1UPFtj //object
user:{58}
I'm trying to fetch data from the session key and i'm getting Undefined , like this:
redis_model.prototype.getAll = function () {
client.keys('*', function (err, keys) {
if (err) return console.log(err);
console.log(keys['session']); // tried also keys.session
});
};
The part that i can't figure out is why i get Type String for all the keys - like here:
redis_model.prototype.getAll = function () {
client.keys('*', function (err, keys) {
if (err) return console.log(err);
console.log(typeof keys[i]); result : //string,string, string,string
});
};
I've tried HGETALL to get the keys as objects but i still get undefined :
redis_model.prototype.getAll = function () {
client.hgetall("session",function(data){console.log(data)});
};
Here is a screenshot of the redis db...
Client.keys("*",function(err,keys){})
This just returns all the keys present in the redisDB which are basically strings
Instead you can use
client.get('key',function(err,data){})
inorder to get the result as an object it should be stored as a hash i.e
client.hmset("session",{'php':'cf5myWFkDNEPwiRLpi6M1P6LqX1UPFtj'}
client.hgetall("session",function(data){console.log(data.php)})
the above code gives you the value assigned to php.
Got it....
redis_model.prototype.getAll = function () {
client.get('session:php:VfAPTh_NLpBrcq3VGHTC8uT7c-sF4bQd', function(err,
result){
var foo = (JSON.parse(result))['user'];
console.log( foo);
});
};
Background
I have taken some sample data from a large XML response I will be working with in my app. I decided to save the xml to a response.xml file in my app so I can parse the data without making a bunch of unnecessary request to the api.
I am going to be using xml2js to convert the xml response to a JS Object.
Problem
I have been able to open the file and console.log() it.
I have been able to run xml2js by passing a small xml string to it which I also console.log() it.
But I have only been able to console.log() the file after xml2js creates the object. No matter what I try I continue to get null when using return or passing trying to pass the data outside of the initial creation of the object.
Example
This prints xml tree to the console,
var fs = require('fs');
var openFile = fs.readFile('./response.xml', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
function requestCreditReport() {
return openFile;
}
requestCreditReport();
This prints a small xml string to console statically added in with
xml2js,
var parseString = require('xml2js').parseString;
var xml = "<root>Hello xml2js!</root>";
parseString(xml, function (err, result) {
console.dir(result);
});
Question
How do I use the object once it is created outside of the method below. Initially when it is created I can output it to the console but cannot seem to access it outside of that console.log(). in the example below I am trying return result. This leaves the value null when I try to pass the object returned by the function to a variable like this,
var response = requestReport();
Recent try,
var fs = require('fs');
var parseString = require('xml2js').parseString;
function requestReport() {
fs.readFile('./response.xml', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
return parseString(data, function (err, result) {
return result;
});
});
}
var response = requestReport();
console.log(response);
This returns null. But if I console.log(result) instead or using return then trying outside of the function it returns this,
{ RESPONSE_DATA:
{ '$': { MYAPI: '0.0.0' },
DETAILS: [ [Object] ],
DETAILS_ACCOUNT: [ [Object] ],
RESPONSE: [ [Object] ] } }
requestReport is async. It doesn't return anything so response is undefined.
You have to use a callback.
var fs = require('fs');
var parseString = require('xml2js').parseString;
function requestReport(callback) {
fs.readFile('./response.xml', 'utf8', function(err, data) {
if (err) return callback(err);
parseString(data, callback);
});
}
requestReport(function(err, result) {
if (err) return console.error(err);
console.log(result);
});
I want to use an module to get and process data from my MongoDB database. (It should generate an object that represents my Express.js site's navbar)
I thought of doing something like this:
var nav = { Home: "/" };
module.exports = function() {
MongoClient.connect(process.env.MONGO_URL, function(err, db) {
assert.equal(err, null);
fetchData(db, function(articles, categories) {
combine(articles, categories, function(sitemap) {
// I got the data. What now?
console.log("NAV: ", nav);
})
});
});
};
var fetchData = function(db, callback) {
db.collection('articles').find({}).toArray(function(err, result) {
assert.equal(err);
articles = result;
db.collection('categories').find({}).toArray(function(err, result) {
assert.equal(err);
categories = result;
db.close();
callback(articles, categories);
});
});
};
var combine = function(articles, categories, callback) {
categories.forEach(function(category) {
nav[category.title] = {};
articles.forEach(function(article) {
if(article.category == category.name) {
nav[category.title][article.title] = "link";
}
})
});
callback(nav);
};
As of line 6, I do have all data I need.
(An object, currenty like { Home: '/', Uncategorized: { 'Hello world!': 'link' } })
But since I'm in an anonymous function, I don't know how to return that value. I mean, return would just return it the function that called it... And in the end, MongoClient.connect would receive my data.
If I set a variable instead, it would be set as module.exports returned before Node can even query the data from the database, right?
What can I do in order to make this work?
It should result in some kind of function, like
var nav = require('nav');
console.log(nav());
Thanks in advance!
Add another callback:
var nav = { Home: "/" };
module.exports = function(cb) {
MongoClient.connect(process.env.MONGO_URL, function(err, db) {
assert.equal(err, null);
fetchData(db, function(articles, categories) {
combine(articles, categories, function(sitemap) {
cb(sitemap);
})
});
})
});
And then use this way:
var nav = require('nav');
nav(function(sitemap){ console.log(sitemap); });
You can use mongoose module or monk module. These modules have been tested properly .
Just use
npm install mongoose or monk
The suggestion about mongoose is great and you can look into it, however I think you've already done the job with the fetching of the data from the db. You just need to access it in your main node flow.
You can try this:
module.exports.generateNav = function() {
MongoClient.connect(process.env.MONGO_URL, function(err, db) {
assert.equal(err, null);
var output = fetchData(db, function(articles, categories) {
combine(articles, categories, function(sitemap) {
})
});
return (output);
});
};
And then in your main application you can call it in the following way:
var nav = require('nav');
navigation = nav.generateNav();
console.log(navigation);
I'm trying to understand how to wait for http requests to finish in node. I want to make two http requests and use the results in a function that gets called after the http requests are finished.
I'm using async and request and have been using async.series as following:
var request = require("request");
var express = require('express');
var async = require("async");
app.get('/rx', function(req, res) {
var drug1 = req.query.drug1;
var drug2 = req.query.drug2;
console.log("in rx")
console.log(drug1);
console.log(drug2);
var id1 = '';
var id2 = '';
/*part of code I'm concerned with*/
async.series([
function(callback) {
id1 = getID(drug1);
console.log("function one");
console.log(id1);
callback();
},
function(callback) {
id2 = getID(drug2);
console.log("function two");
console.log(id2);
callback();
}
],
function(err, results) {
console.log(id1);
console.log(id2);
request("http://rxnav.nlm.nih.gov/REST/interaction/interaction.json?list?rxcuis=" + id1 + "&sources=" + id2, function(error, response, body) {
console.log("finished!");
res.json(body);
});
});
});
//returns an int ID
function getID(drugName) {
request("http://rxnav.nlm.nih.gov/REST/Prescribe/rxcui.json?name=" + drugName, function(error, response, body) {
var content = JSON.parse(body);
var id = parseInt(content.idGroup.rxnormId);
console.log("in getID function");
console.log(id);
return id;
});
}
The console output shows:
in rx
advil
ibuprofen
seriesone
undefined
two
undefined
undefined
undefined
finished!
GET /rx?drug1=advil&drug2=ibuprofen 304 345ms
in getID function
153010
in getID function
5640
I want to wait until each http request function is completed, and then proceed to the next portion of code. How do I achieve this?
This question (or variants thereof) has been asked more than 1000 times here on StackOverflow. Therefore I'm not going to explain it but you can search "return async" on this site (the search input at the top right corner) if you want to know more.
The basic problem is that it's impossible to return values from an async function (ever wonder why they accept callbacks?).
For your specific case, you need to change getId() to:
//returns an int ID
function getID(drugName, callback) {
request("http://rxnav.nlm.nih.gov/REST/Prescribe/rxcui.json?name=" + drugName, function(error, response, body) {
var content = JSON.parse(body);
var id = parseInt(content.idGroup.rxnormId);
console.log("in getID function");
console.log(id);
callback(null,id); // <--- this is how you return async values
});
}
Note: the null is because functions in the async.js family expects the first argument to the callback to be an error. So if there are no errors pass null. This by the way is a standard node.js practice.
Then inside async.series() you do:
async.series([
function(callback) {
getID(drug1,callback);
},
function(callback) {
getID(drug2,callback);
}
],
function(err, results) {
console.log(results[0]); // id1
console.log(results[1]); // id2
// do the rest..
});
I have a problem in getting a .json file in express and displaying in a view. Kindly share your examples.
var fs = require("fs"),
json;
function readJsonFileSync(filepath, encoding){
if (typeof (encoding) == 'undefined'){
encoding = 'utf8';
}
var file = fs.readFileSync(filepath, encoding);
return JSON.parse(file);
}
function getConfig(file){
var filepath = __dirname + '/' + file;
return readJsonFileSync(filepath);
}
//assume that config.json is in application root
json = getConfig('config.json');
Do something like this in your controller.
To get the json file's content :
ES5
var foo = require('./path/to/your/file.json');
ES6
import foo from './path/to/your/file.json';
To send the json to your view:
function getJson(req, res, next){
res.send(foo);
}
This should send the json content to your view via a request.
NOTE
According to BTMPL
While this will work, do take note that require calls are cached and will return the same object on each subsequent call. Any change you make to the .json file when the server is running will not be reflected in subsequent responses from the server.
This one worked for me. Using fs module:
var fs = require('fs');
function readJSONFile(filename, callback) {
fs.readFile(filename, function (err, data) {
if(err) {
callback(err);
return;
}
try {
callback(null, JSON.parse(data));
} catch(exception) {
callback(exception);
}
});
}
Usage:
readJSONFile('../../data.json', function (err, json) {
if(err) { throw err; }
console.log(json);
});
Source