Splitting a var into another var that contains only numbers - javascript

Currently I'm getting my data out of a SQL Server 2012 using a powershell and the mssql plugin. I'm trying to extract out data using queries, so I had a query to get the particular information and then use express.js to send the data over to a textbox. This is the code currently.
Server.JS
app.get('/Warning', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'Atiqah',
password: 'password',
server: 'DESKTOP-5045H9Q',
database: 'TestDB'
};
// connect to your database
sql.connect(config, function (err) {
var record;
if (err) console.log(err);
// create Request object
var request = new sql.Request();
var stringrequest =
// query to the database and get the records
request.query("SELECT COUNT([EntryType]),EntryType FROM TestTable GROUP BY EntryType", function (err, recordset) {
if (err) console.log(err)
// send records as a response
record = recordset;
console.log("You are currently connected to " + JSON.stringify(config));
res.send(JSON.stringify(recordset));
//console.log("Query submitted is " + JSON.stringify(stringrequest));
});
});
Index2.html
function myFunction() {
$.get("/Warning", function (string) {
$('#txtWarning').val(string);
});
}
<body onload="myFunction()">
<textarea rows="8" cols="70" id="txtWarning"></textarea></body>
The data that i get out of the textbox would be something like this:
{"recordsets":[[{"":734,"EntryType":"\"Warning\""},{"":1049,"EntryType":"\"Error\""}]],"recordset":[{"":734,"EntryType":"\"Warning\""},{"":1049,"EntryType":"\"Error\""}],"output":{},"rowsAffected":[2]}
How do I go around only getting the numbers out of this var? Any help would be much appreciated. The output that I wanted would look something like this.
734, 1049, 734, 1049.

Simple solution:
var data = {}; //your object here
var nums = [];
Object.keys(data)
.filter(x => Array.isArray(data[x]))
.forEach(x => {
data[x].forEach(y => {
nums.push(y[""]);
})
});

Related

Using mssql PreparedStatement in Node.js returning odd data

I am working on using a PrepareStatement in Node to protect against SQL injections:
let conn = sql.connect(config[2], function (err) {
var ps = new sql.PreparedStatement(conn);
let placeholders = {
param: "*",
};
ps.input('param', sql.VarChar(20));
let query = "SELECT #param FROM table"
ps.prepare(query, (err1) => {
ps.execute(placeholders, (err2, recordset) => {
console.log(recordset.recordsets);
ps.unprepare((err3) => {
console.log('disconnected!');
})
})
});
When I run this I'm expecting the recordset to contain all of the data in 'table', but instead a list of {'': '*'} is returned, with a length equal to the number of rows in table.
If I replace the '#param' in query with a '*', then the correct data is returned, so I'm assuming I'm doing something wrong with the PreparedStatement.
Note: I'm accessing an SQL server in Azure

Updating content from JSON files by using the filesystem module in NodeJs

I have a small JSON file
{
"users": [
{
"id": 1111,
"name": "Foo",
"gold": 2
},{
"id": 2222,
"name": "Bar",
"gold": 7
}
]
}
and want to manipulate the data of one specific object, selected by its id.
I want to
read the data from the file
manipulate the data
write the new data back to the file
send a response to the client
so I went for this route, called by using Ajax
app.get('/incG/:id', function (req, res) {
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var user = users.find(u => u.id === Number(req.params.id)); // get the user by id
user.gold++; // increase his value
fs.writeFile('./database.json', , (err) => { // the second parameter is missing!
res.send(user.gold); // send a response to the client
});
});
});
As you can see, when using fs.writeFile(database, , (err) => { the second parameter is missing.
What do I have to pass in there? I just want to update one specific user object (one specific value).
EDIT
When passing in JSON.stringify(user) as a parameter I delete all the data in the file and just write down the new object. So this might not work this way.
Try this,
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var userGold;
users.find(u => {
if (u.id === Number(req.params.id)) {
userGold = u.gold++;
}
});
users = JSON.stringify(users);
fs.writeFile('./database.json', users, (err) => {
res.send(userGold);
});
});
fs.writeFile(file, data[, options], callback)
Pass stringified JSON as second argument.
app.get('/incG/:id', function(req, res) {
fs.readFile('./database.json', 'utf8', function(err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var user = users.find(u => u.id === Number(req.params.id)); // get the user by id
user.gold++; // increase his value
var dataToWrite = JSON.stringify(user);
fs.writeFile('./database.json', dataToWrite, (err) => { // the second parameter is missing!
res.send(user.gold); // send a response to the client
});
});
});

Sending an AlchemyData News query using Node.js (watson-developer-cloud module)

I'm currently working with Node.js using the watson-developer-cloud Node.js SDK and I'm having problems when sending a query that includes an entity.
This is my code:
// require watson's node sdk and fs
var watson = require('watson-developer-cloud');
var fs = require('fs');
// Define output file
var outputJSONFile = '/home/vagrant/Desktop/node/dir/data.json';
// Create alchemy_data_news object using our api_key
var alchemy_data_news = watson.alchemy_data_news({
api_key: ''
});
// Define params for the query and what values to return
// Accepted returne values:
// docs.alchemyapi.com/v1.0/docs/full-list-of-supported-news-api-fields
var params = {
start: 'now-1m',
end: 'now',
count: 2,
qs: ['q.enriched.url.enrichedTitle.entities.entity.text=apple'],
return: ['enriched.url.url,enriched.url.title']
};
// Call getNews method and return json
alchemy_data_news.getNews(params, function (err, news) {
if (err) {
console.log('error:', err);
} else {
fs.writeFile(outputJSONFile, JSON.stringify(news, null, 2), function(err) {
if (err) {
console.log('WriteFile Error:', err);
} else {
console.log("JSON saved to " + outputJSONFile);
}
});
}
});
I'm still trying to figure out how to send the entities parameters using the params object.
While digging up through some code I came across qs so I have been using that to test but I haven't had success at all.
Any suggestions are greatly appreciated.
P.S: I'm trying to pass:
q.enriched.url.enrichedTitle.entities.entity.text=apple
q.enriched.url.enrichedTitle.entities.entity.type=company
If you look at the node-sdk source code for AlchemyDataNews, you will see that the top level parameters are being sent as query strings.
Then params map should be:
var params = {
start: 'now-1m',
end: 'now',
count: 2,
return: ['enriched.url.url,enriched.url.title'],
// fields here
'q.enriched.url.enrichedTitle.entities.entity.text': 'apple',
'q.enriched.url.enrichedTitle.entities.entity.type': 'company'
};

How to get attributes of a Neo4j node

I am making a connection to the neo4j in Nodejs to get the attribute of ServiceConsumer node. But not sure, how to do it. here is my code which connect to the neo4j. Suppose ServiceConsumer has some attributes like city, state, name, userId and I have to retrieve the name of ServiceConsumer. I am getting the userId from the frontend and on the basis of this userId querying the neo4j database to get the node information.How would i get the name of ServiceConsumer? Any help ll be appreciated.
var user = this.userId;
var request = require("request");
var host = 'localhost';
port = 7474;
var httpurlforconnection ='http://' + host + ':' + port + '/db/data/transaction/commit';
/*Let’s define a function which fires the cypher query.*/
function runCypherQuery(query, user, callback) {
request.post({
uri: httpUrlForTransaction,
json: {statements: [{statement: query, parameters: user}]}
},
function (err, res, body) {
callback(err, body);
})
}
// Let’s fire some queries below
runCypherQuery(
'MATCH (n:ServiceConsumer {userId : {} }) RETURN n', {
userId: 'user',
}, function (err, resp) {
if (err) {
console.log(err);
} else {
console.log(resp);
}
}
);
Take a look at How to return all properties of a node with their name and their value using Cypher
You can do the same thing using nodejs, simple POST can return the whole node to you and then simply cast it to an object using JSON.
By the way, your code is working fine, you can simply take the "resp" object which should contain the result JSON.
One obvious thing that I see is that you're not specifying the userId parameter. You Cypher should look something like this:
MATCH (n:ServiceConsumer {userId: {user_id}}) RETURN n
Does that help?

Javascript nodejs tedious mssql is there a way to get json?

I'm using nodejs and tedious connector to get data from mssql server. In documentation, I only see this one way to retrieve data
var request = new Request("select Name, Value, Article_Id from [tableone] where Id = '1'", function (err, rowCount, rows) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function (rows) {
...
bigArrat.push(JSON.stringify(rows));
});
But in my example I want all rows, not only one property but more. Currently, it return in separate row one cell eg. rows[0].value will return Name, rows[1].value Value ... for me it is rubbish.
I want to get all information in json array of object not all metadata or one property. There is a way to do this or there is a better connector for nodejs and sqlserver ?
The rows value sent to your initial callback is the array of rows being sent back:
var request = new Request("select Name, Value, Article_Id from [tableone] where Id = '1'", function (err, rowCount, rows) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
console.log(rows) // this is the full array of row objects
// it just needs some manipulating
jsonArray = []
rows.forEach(function (columns) {
var rowObject ={};
columns.forEach(function(column) {
rowObject[column.metadata.colName] = column.value;
});
jsonArray.push(rowObject)
});
return callback(null, rowCount, jsonArray);
});
In Sql Server 2016 you can format query results as JSON text using FOR JSON option, see https://msdn.microsoft.com/en-us/library/dn921882.aspx
You just need to read JSON fragments returned by query.
Add this to your config.
rowCollectionOnRequestCompletion: true
var config = {
userName: '', // update me
password: '', // update me
server: '', // update me
options: {
database: '', // update me
encrypt: true,
rowCollectionOnRequestCompletion: true
}
}
Then on your query you can now get the data of rows.
var executeQuery = (res,query) => {
request = new Request(query, (err, rowCount, rows) => {
console.log("Rows: ", rows);
res.send(rows);
});
connection.execSql(request);
}
I learned it from:
http://tediousjs.github.io/tedious/api-request.html
EDIT
Update not to have metadata:
var data = []
request = new Request(query, (err, rowCount, rows) => {
if(err) {
console.log(err)
res.send({ status: 500, data: null, message: "internal server error."})
} else {
console.log(rowCount+' row(s) returned')
res.send({ status: 200, data: data, message: "OK"})
}
})
request.on('row', function(row){
data.push({
last_name: row[0].value,
first_name: row[1].value
})
})
connection.execSql(request)
If you are using express on server side I can recommend using express4-tedious (see https://www.npmjs.com/package/express4-tedious). It allows to easily write apis for SQL connections with small code and streams json result to response.
Connection:
var express = require('express');
var tediousExpress = require('express4-tedious');
var app = express();
app.use(function (req, res, next) {
req.sql = tediousExpress(req, {connection object});
next();
});
Example Api:
/* GET from tableone, streams json result into response */
router.get('/', function (req, res) {
req.sql("select Name, Value, Article_Id from [tableone] where Id = '1' for json path")
.into(res);
});
You can then call these apis e.g. from frontend.
I tried that way but it did not work for me perhaps my knowledge of js and callbacks is not good enough. So, here is my solution. I had to add things to my config of connection to make rows of request work. You would also have to do this. Go to: at the end of new Request section, and to the rows.
here
Second thing, I did is pretty simple.
var jsonArray = [];
var rowObject= {};
var request = new Request("SELECT TOP 5 * FROM tableName",function(err,rowCounts,rows)
{
if (err)
{
console.log(err);
}
else
{
console.log(rowCounts + " rows returned");
}
//Now parse the data from each of the row and populate the array.
for(var i=0; i < rowCounts; i++)
{
var singleRowData = rows[i];
//console.log(singleRowData.length);
for(var j =0; j < singleRowData.length; j++)
{
var tempColName = singleRowData[j].metadata.colName;
var tempColData = singleRowData[j].value;
rowObject[tempColName] = tempColData;
}
jsonArray.push(rowObject);
}
//This line will print the array of JSON object.
console.log(jsonArray);
and to show you how my connection.config looks like:
static config: any =
{
userName: 'username',
password: 'password',
server: 'something.some.some.com',
options: { encrypt: false, database: 'databaseName' ,
rowCollectionOnRequestCompletion: true }
};//End: config
and this is how I am passing it to connection.
static connection = new Connection(Server.config);
Complementing the answer from #Jovan MSFT:
var request = new Request('select person_id, name from person for json path', function(err) {
if (err) {
console.log(err);
}
connection.close();
});
And, finally, in the row event:
request.on('row', function(columns) {
var obj = JSON.parse(columns[0].value);
console.log(obj[0].name);
});
P.S.: the code above does not iterate over columns parameter because for json path returns a single array of objects in a single row and column.
Applying map-reduce function in returned rows:
rows.map(r=>{
return r.reduce((a,k)=>{
a[k.metadata.colName]=k.value
return a
}
,{})
})
This is a combination of a few responses above. This uses FOR JSON AUTO in the SELECT statement and parses the "column" as JSON. The row/column nomenclature may be a bit misleading for folks unfamiliar with this API. In this case, the first "columns" value will be an array of the rows in your table:
var request = new Request("SELECT Name, Value, Article_Id FROM [tableone] WHERE Id = '1' FOR JSON AUTO", function (err, rowCount, rows) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', (columns) => {
const json = JSON.parse(columns[0].value);
});

Categories