Express.js pass key name from a variable value in a route - javascript

I'm trying to dynamically pass key name in a route but it is always giving me undefined
This is the code I have tried but cannot seem to get it right. The dynamic name I am trying to pass is arrayname which will changed based on the parameter
router.get('/searchterm/table/:table/term/:term/fields/:fields/render/:render/arrayname/:arrayname', function (req, res, next) {
var pagetorender = req.params.render;
var arrayname = req.params.arrayname;
db.query('select * from ' + req.params.table + ' where ' + strfields, function (err, result) {
if (err) {
res.send(err)
} else {
console.log(arrayname)
console.log(result.rows)
res.render(pagetorender, { arrayname: result.rows })
}
})
})
For example, if I have to pass
res.render(pagetorender, { test123: result.rows })
It would be like
var arrayname = "test123";
res.render(pagetorender, { arrayname: result.rows })

you can get the params with req.param("param name"); so try something like this
router.get('/searchterm/table/:table/term/:term/fields/:fields/render/:render/arrayname/:arrayname', function (req, res, next) {
var pagetorender = req.param("render");
var arrayname = req.param("arrayname");
db.query('select * from ' + req.params.table + ' where ' + strfields, function (err, result) {
if (err) {
res.send(err)
} else {
console.log(arrayname)
console.log(result.rows)
res.render(pagetorender, { arrayname: result.rows })
}
})
})
the key change is :
var pagetorender = req.param("render");
var arrayname = req.param("arrayname");

Related

boolean from function is returning undefined node.js

I have 2 functions... 1st one in auth.js, which does this:
const adminCheck = (req, res) => {
console.log(“one”)
UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => {
if(response) {
return true
} else {
return false
}
})
}
module.exports = {
adminCheck
}
basically checks if the user is an admin in my table. that works, but I am trying to retrieve the boolean in my function in my index.js function, which is below.
router.get(‘/viewRegistration’, auth.ensureAuthenticated, function(req, res, next) {
console.log("authcheck: " + auth.adminCheck())
const user = JSON.parse(req.session.passport.user)
var query = “SELECT * FROM tkwdottawa WHERE email = ‘” + user.emailAddress + “’”;
ibmdb.open(DBCredentials.getDBCredentials(), function (err, conn) {
if (err) return res.send(‘sorry, were unable to establish a connection to the database. Please try again later.’);
conn.query(query, function (err, rows) {
if (err) {
Response.writeHead(404);
}
res.render(‘viewRegistration’,{page_title:“viewRegistration”,data:rows, user});
return conn.close(function () {
console.log(‘closed /viewRegistration’);
});
});
});
})
where I am logging the value in the console.log right under where I initialize the function, it is returning undefined. how can I fix this?
You need to use Promise and wrap all callbacks to actually return a given result value from a function that uses a callback because usually a callback is called asynchronously and simply returning a value from it does not help to catch it in a calling function.
const adminCheck = (req, res) => {
console.log(“one”)
return new Promise(resolve, reject) => {
UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => {
if(response) {
resolve(true)
} else {
resolve(false)
}
})
}
});
then you need to await a result calling this function using await keyword and marking a calling function as async:
router.get(‘/viewRegistration’, auth.ensureAuthenticated, async function(req, res, next) {
console.log("authcheck: " + await auth.adminCheck())
const user = JSON.parse(req.session.passport.user)
var query = “SELECT * FROM tkwdottawa WHERE email = ‘” + user.emailAddress + “’”;
ibmdb.open(DBCredentials.getDBCredentials(), function (err, conn) {
if (err) return res.send(‘sorry, were unable to establish a connection to the database. Please try again later.’);
conn.query(query, function (err, rows) {
if (err) {
Response.writeHead(404);
}
res.render(‘viewRegistration’,{page_title:“viewRegistration”,data:rows, user});
return conn.close(function () {
console.log(‘closed /viewRegistration’);
});
});
});
})
That's simple. You just forgot to return the inner function's return value
const adminCheck = (req, res) => {
console.log(“one”)
return UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => {
if(response) {
return true
} else {
return false
}
})
}
module.exports = {
adminCheck
}

Node.js query INSERT callback not working as expected

Small problem when using POST and adding an INSERT. Works as below, but want to use a callball after the data has been inserted. At the moment the database is being updated. (good) but can't use the callback - I would expect this to be just below the throw error. So you could use result.insertId. Any thoughts welcome?
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if (error)throw error;
//*** when I add response here get 502 bad gateway error.
});
res.sendStatus(200);
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
res.sendStatus(error);
});
});
try this way :
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if(error){
return res.status(500).send(error);
}
if(!error && results){
return res.status(200).send(results);
}
});
});
}).catch(function(error) {
return res.status(500).send(error);
});
});
if you want to use callback then ,create a separate function like :
var insertData = function(query,data,callback){
db.query(query, data, function (error, results, fields) {
if(error){callback(error,null);}
if(!error && results){callback(null,results);}
});
});
and call this way inside getID :
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
insertData('INSERT INTO cu_groups SET ?', post, function (error,data){
if(error){
return res.status(500).send(error);
}
if(data){
return res.status(200).send(data);
}
});
});
Working code below many thanks to Saurabh Mistry. I removed the SET post and added the table fields and values explicity.
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
// query
let query = "INSERT INTO cu_groups (ID, name) VALUES('" + ID + "','" + name + "')";
// execute query
db.query(query, (error, result) => {
if(error){
return res.status(500).send(error);
}
if(!error && result ){
return res.send(result);
}
});
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
return res.status(500).send(error);
});
});

Object context lost inside of function

router.get("/", function(req, res, next) {
axios.get('https://www.behance.net/v2/users/user/projects/4889175?api_key=' + 'API')
.then(function(response) {
var data = response.data.projects;
for(var i=0;i < data.length; i++) {
Behance.findOne({ name: data[i].name }, function(err, user) {
if (err) { return next(err); }
if (!user) {
console.log(this.name);
// var newBehance = new Behance({
// name: this.name,
// });
// newBehance.save(next);
}
});
}
})
.catch(function(error) {
console.log(error);
});
});
I'm pulling projects from Behance w/ their API and trying to save each one to a DB if it doesn't already exist using findOne. Inside of the for loop data[i].name returns a value, but inside of the findOne function it returns undefined.
I can't seem to figure out why this is happening..
I think the problem is that you're logging out this.name instead of data[i].name. As far as I can tell, this is window.
You can use .forEach to simplify things a bit:
router.get("/", function(req, res, next) {
axios.get('https://www.behance.net/v2/users/user/projects/4889175?api_key=' + 'API')
.then(function(response) {
response.data.projects.forEach(({name}) => {
Behance.findOne({ name }, function(err, user) {
if (err) { return next(err); }
if (!user) {
console.log(name);
// var newBehance = new Behance({
// name,
// });
// newBehance.save(next);
}
});
}
})
.catch(function(error) {
console.log(error);
});
});

angularjs: match text with array of values

exports.searchcomments = function (req, res) {
var searchText = !!req.params && req.params.searchtext || null;
var matchedComments = [];
ReferenceValue.find({ domaincode: 'DEPOSITCMNTS' })
.lean()
.exec(function (error, refValueDocs) {
if (!!error) {
billingUtils.doErrorResponse({
error: 'ERRORS.REFUNDABLEAMOUNT'
}, req, res, error);
} else {
for (var i = 0; i < refValueDocs.length; i++) {
refValueDocs[i].valuedescription = new RegExp('^' + searchText, 'i')
}
}
})
};
while exec the query, i will get refValueDocs which is array. I want to check refValueDocs[i].valuedescription matches with searchText. And also matched ones are to be pushed into an matchedComments array. How do I check the searchText matches with refValueDocs[i].valuedescription?
You can use filter to filter values in an array and it will return new array containing filtered objects.
exports.searchcomments = function (req, res) {
var searchText = !!req.params && req.params.searchtext || null;
var matchedComments = [];
ReferenceValue.find({ domaincode: 'DEPOSITCMNTS' })
.lean()
.exec(function (error, refValueDocs) {
if (!!error) {
billingUtils.doErrorResponse({
error: 'ERRORS.REFUNDABLEAMOUNT'
}, req, res, error);
} else {
matchedComments = refValueDocs.filter(function(doc){
var regex = new RegExp('^' + searchText, 'i');
return doc.valuedescription.match(regex);
});
}
})
};

Creating a user with POST , but it's not working correctly

I'm creating a new user with POST and the program tells me it's created correctly , but when I check with GET if the user was created , it creates an empty {} entry. What can be wrong here?
app.get(BASE_API_PATH + "/contacts", (req, res) => {
console.log(Date() + " - GET /contacts");
db.find({}).toArray((err, contacts) => {
if (err) {
console.error("Error accesing DB");
res.sendStatus(500);
return;
}
res.send(contacts.map((c) => {
delete c._id;
return c;
}));
});
});
app.post(BASE_API_PATH + "/contacts", (req, res) => {
console.log(Date() + " - POST /contacts");
var contact = req.body;
if (!contact) {
console.log("warning : new Get req");
res.sendStatus(400);
}
db.find({ "name": contact.name }).toArray((err, contacts) => {
if (err) {
console.log("error accesing db");
res.sendStatus(400);
}
if (contacts.length > 0) {
console.log("warning");
res.sendStatus(409);
}
else {
db.insert(contact);
res.sendStatus(201);
}
});
});

Categories