How to get attributes of a Neo4j node - javascript

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?

Related

How to check whether request url params are not null in node js app?

I am new to node js programming and trying to develop an API using node js, I am able to retrieve the expected output from the built API but I would like to perform some exception handling. For that I would like to check whether the request params coming from URL are not null. Below is my code:
async function getDetails(input) {
// using knex to execute query
return queries.getbymultiwhere('table_name',{
name:input.name,
id:input.id,
role:input.role
})
}
router.get('/:name/:id/:role',(req,res)=>{
getDetails({
name:req.params.name,
id:req.params.id,
role:req.params.role}).then(Results=>{ Do something with results}
})
In above code I want to check that name, id and role param values are not null.
Any helpful solution will be appreciated.
Thank you!
You can create a middleware which checks those parameters.
function check(fields) {
return (req, res, next) => {
const fails = [];
for(const field of fields) {
if(!req.query[field]) {
fails.push(field);
}
}
if(fails.length > 0){
res.status(400).send(`${fails.join(',')} required`);
}else{
next();
}
};
}
app.get('/api', check(['name', 'id', 'role']), (req, res) => {
getDetails()...
});

How to list the listUsers Cognito Identity Service provider?

I have this code in which I have used the cognitoidentityserviceprovider Method known as listUsers which returns a list of all my cognito users. Below is the code.
createPatient = async () => {
var params = {
UserPoolId: 'xxxxxxxxxxxxxxxxxxxx',
AttributesToGet: [ "email" ],
Filter: "",
Limit: 10
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.listUsers(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
})
}
Now on one hand I would like to know how I can return the result in e.g a <div></div> like when one returns the values of a listquery when dealing with graphql queries.
On the other hand I would like to know how I could create form which takes in the data (UserpoolId, AttributesToGet, Filter, Limit) and maps the values to params so that e.g a user could fill them out himself.
Hope I have expressed myself well. Thanks a lot for any help.

How to get results from MySql DB using and send them back to API.ai

I need some assistance in figuring out the syntax for SQL queries while using them through an api.ai webhook & connecting to a Google cloud Mysql database.
Although the query is working, the 'request gets timed out'
'use strict';
const mysql = require('mysql');
exports.name = (req, res) => {
let action = req.body.result['action'];
if (action === 'apple') {
callDB().then((output) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(output));
}).catch((error) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(error));
});
}
};
function callDB() {
return new Promise((resolve, reject) => {
try {
var connection = mysql.createConnection({
host: "<host>",
user: "<user>",
password: "<pass>",
database: "<DB>"
});
connection.query("SELECT description AS solution FROM mtable WHERE title LIKE '%Breakfast%'", function (error, results, fields) {
if (!error) {
let response = "The result is: " + results[0].solution;
response = response.toString();
let output = {'speech': response, 'displayText': response};
console.log(output);
resolve(output);
} else {
let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed4.'};
console.log(output);
reject(output);
}
});
connection.end();
} catch (err) {
let output = {'speech': 'try-catch block error', 'displayText': 'try-catch block error3'};
console.log(output);
reject(output);
}
}
);
}
If i substitute the query with this, it works :
'SELECT description AS solution FROM mtable WHERE id LIKE 1001'
id is a column name with only id`s
title is a column name with titles such as Breakfast wrap, etc.
this is part of the error shown on webhook json:
"metadata": {
"intentId": "<id>",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 5000,
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Request timeout.",
"webhookTimedOut": true
},
I referenced the following thread for the code,
How to get results from MySql DB using node.js MySQL and send them back to API.ai
There seems to be a typo in your query string declaration (near '%Breakfast%'') :
connection.query('SELECT description AS solution FROM mtable WHERE title LIKE '%Breakfast%'', function (error, results, fields) {
When assigning your query string to a variable, 'SELECT description AS solution FROM mtable WHERE title LIKE '%Breakfast%'' is interpreted as a number (because of the % operator).
Does fixing your single quotes help in any way?
connection.query("SELECT description AS solution FROM mtable WHERE title LIKE '%Breakfast%'", function (error, results, fields) {
Problem has to be on your server side with mysql. I do this daily and it works just fine with mysql in under 5 seconds for queries.
Could be your where clause is creating full table scans, thus timing out back to Diagflow (>5 seconds) or the db connection is falling out.
You need to set timers in front of the routine and the end cycle, look at your durations. Run your query from a bash script alone and see how long it takes. You'll find where the timeout is happening. Having search parms (%) on both sides of the criteria will definitely take longer than a search string start only (meaning search starting with) vs. %search% (find any substring that contains).
Good luck.

Use the Node.js + PostgreSQL to get by id

I am trying to write an application with Node.js & PostgreSQL, currently I faced a problem in get by id, below is my code
app.get('/monsters/:id', (request, response, next) => {
const { id } = req.params;
pool.query('select * from monsters where id = $1', [id], (err, res) => {
if (err) {
return next(err);
}else {
response.json(res.rows);
}
});
});
it supposed to get the id I typed and return the value I stored in database with a table name called monster, however it just kept returning a blank object {}, I found the problem may because of the $1 part since my atom seemed not able to recognize $, what can I do to fix this problem or is there other way to write this instruction? Thank you!

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'
};

Categories