How to call a function at start in Node-Express, with dbconnection - javascript

I'm a little bit newbie with Nodejs. I'm working in a Nodejs - express solution (as webservice of an angularjs web). I want to send and e-mail when MSSSQL database query gives back some information. This is working well for me. The problem is this function should be call in the app.js (when the nodejs server starts), because the function don't should respond to any frontend/web call.
The function:
exports.sendMailBuy = function(req, res) {
//do stuff
}
The app.js
var silkcartCtrl = require('./controllers/silkcart.controller');
I need to connect with the database, so I've tried to call the funciont in the same function db connection (I'm using Tedious):
dbsqlservertoken.connect().then(function(err, req, res) {
console.log('Connection pool open for sql server');
silkcartCtrl.sendMailBuy(req, res);
}).catch(function(err) {
console.error('Error creating connection pool', err);
});
With this call I reach the function in the controller, but the req and res vars are empty, so the connection could not be done.
Any help will be appreciate.
Thanks in advance.

The .then() method is used when a Promise is returned. I'm not familiar with the libraries you're using, but your code indicates that connect() returns a Promise.
See Promises for more information.
In particular, the function passed to .then() takes a single argument which is the result resolved by the Promise. In your code, err is being assigned the result while req and res are undefined because the function only receives one argument.

req, res are not returned from connect callback function they are only acccessed using api requests e.g. app.post('/any route' , function(req, res))
You can use node_mailer module if you need req object to send email because with node_mailer you can send email without req object

Related

NodeJS Express Api -- calling res.send outside route works but res.status does not work no matter what

To keep things clean in my express route page I have a local function that is called in every route and it passes the sql query together with the req and res objects.
This works fine for sending a successful result and calling res.send works.
The problem that I'm having is I can't seem to find a way to get res.status to work and no matter the syntax it simply times-out and gives no error whatsoever in the console OR on the front end.
The tricky thing is, when it's inside the specific route it does work but the error message does not seem to get sent through instead it's just blank body?
`async function queryDatabase(queryParam, req, res) {
try {
const cp = new sql.ConnectionPool(config);
await cp.connect();
let result = await cp.request().query(queryParam);
cp.close();
res.send(result.recordset);
} catch (err) {
res.statusMessage = `Database error: ${err}`;
res.status(520);
}
}`
res.status(520) only sets the status value in the response object. It does not actually send the response. So, to send the response, you have several options. In the more recent versions of Express, you can use this shortcut:
res.sendStatus(520);
This will both set the status and send the response.
But, you can also do this in any version of Express:
res.status(520).end();
Which also sets the status and then sends the response.
You should end your response, use res.status(520).end() instead of res.status(520)

JS, Async (lib), Express. response( ) inside async not working

I tried to call res() after some async stuff finishes, inside Async.waterfall([], cb)
But as it seems, the req/res objects are not available in that scope. I call them from my callback cb.
function (req, res, next) {
var query = req.query;
async.waterfall([
async.apply(userManager.register, query.username, query.email, query.password)
], function (err, result) {
if (err)
console.log(err);
if (err && err.internal == false)
return res(err); //TypeError: res is not a function
console.log(result);
});
The only solution I have in mind is, passing the req/res to my backend, and call it there.
But that would mean that my background code needs to have a req and res object. Moreover it returns something to my server, which is also bad.
Thanks for your help.
Your issue is not about scope. It's that res is not a function so you can't call it like res(err). res is an object with methods. You can send an error response either like this which will go to the default error handler in Express:
next(err)
Or like this:
res.status(500).send("Internal Error occurred").
which sends a 500 status on the response and then sends whatever content you want to describe the error.
I can't think of any circumstance where you want to pass the res object into your backend. Your backend should fetch and return data and then your route handler should turn that data or error into a response.

How are these three JavaScript function arguments use?

I've looked up JavaScript functions and arguments but couldn't find anything to help me understand a function like the one below. You can reference the original tutorial.
createPuppy has three arguments: req, res and next.
function createPuppy(req, res, next) {
req.body.age = parseInt(req.body.age);
db.none('insert into pups(name, breed, age, sex)' +
'values(${name}, ${breed}, ${age}, ${sex})',
req.body)
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one puppy'
});
})
.catch(function (err) {
return next(err);
});
}
That function is being called by a router:
var express = require('express');
var router = express.Router();
var db = require('../queries');
router.get('/api/puppies', db.getAllPuppies);
router.get('/api/puppies/:id', db.getSinglePuppy);
router.post('/api/puppies', db.createPuppy);
router.put('/api/puppies/:id', db.updatePuppy);
router.delete('/api/puppies/:id', db.removePuppy);
module.exports = router;
When db.createPuppy is called, there wasn't any arguments passed.
How do those three arguments fit into this function?
Update: I'm new to Node, JavaScript, pg-promise and express. So it was a bit overwhelming to narrow down where to dig. I came here to get leads on where to narrow my focus in. Thank you!
I believe that (req, res, next) are default arguments in Express.
When you write router.post('/api/puppies', db.createPuppy);, the function createPuppy is not actually called yet. This just establishes what function to call when that method/endpoint is hit.
Express takes care of calling the function and passing in the required arguments to it when you hit the /api/puppies endpoint with a POST.
Hope that helps!
You will be sending that data through a POST request to that endpoint. You can then access the data you pass in through the req.body variable.
You will also need the bodyParser middleware to access the request body. More on that here.. http://expressjs.com/en/api.html#req.body

Why modify request after request.post

Newbie question while trying to understand code created by others. Believe me I tried to understand this. Here goes..
For what reason would someone still call functions like .qs() and .json() in Request - module after we got what we need with .post() and sent the response already. They can't affect the request.post as they are called afterwards, can they?
With my skills I'm not able to understand from response module API docs (v2.22.0) what these actually do.
This is not the whole code but I tried to get the important parts here:
// When request comes to /getthisapge, make external query and return data in JSON format.
var request = require('request');
module.exports = function(app) {
app.get('/getthispage', function(req, res, next) {
var filter = {};
var query = {};
filter.category = req.query.category;
query.onBehalf = req.query.onBehalf;
request.post(URIandoptions, function(error, response, body) {
res.json(body.members)
}).qs(query).json(filter);
}
}
Without knowing exactly what the post function does (unnecessary to your question), you need to look at the order of execution.
request.post(URIandoptions, function (error, response, body){
res.json(body.members)
})
.qs(query) // ?
.json(filter); // ?
The function passed into post() does not get called at that specific moment. It is given to the post() function to do with as it pleases. This means technically that the function may never be called (depends on the api).
qs() and json() both get called upon the returning of the prior function. Usually this type of api means the following:
call post(), passing in a function to be run on completion
call qs() to setup the query details
call json() to tell the post function how to act, which in turn executes the actual post, running the completion function after data has been retrieved.

nodejs calling a variable outside of a scope

I am working with nodejs and in the JS file i have the code below to retrieve data .
when i try to use the data outside the scope it doesn't work i get the content undefined the whloe time ..
var data = {};
request.get({url: 'https://my-host/Mypath'}, function(err, response, body) {
if (err) {
console.error(err);
data.err = err;
}
data= body;
});
console.log('Data: ', data);
My main problem is that i have to send res.render with the data and i need to do multiple requests to the server .
You are making an async call. console.log() is executed before the request. Try moving that console.log into the request callback and it will work.
To use it out of the request function, you need to return a promise. Maybe try the Q tool:
https://github.com/kriskowal/q

Categories

Resources