4
\$\begingroup\$

I'm new to Express and SQL, so I don't know the conventional ways of combining the two. Right now I have done it the following way:

app.get('/login', function (req, res) {
 res.render('login');
});
app.get('/home', function (req, res) {
 res.render('home');
});
app.post('/login', function (req, res) {
 db = new sqlite3.Database(file);
 db.serialize(function () {
 [...]
 db.all(query, function (err, rows) {
 if(rows.length == 1) {
 [...]
 res.render('home', {
 username: rows[0].username
 });
 }
 else {
 res.render('login', {
 message: "Login not successful!"
 });
 }
 });
 });
 db.close();
});

However, I feel like the routing should be separated from the database stuff. What should I do different? Or is this normal?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 9, 2017 at 13:44
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

For larger projects this can get very complicated and nasty. You can refactor the db access into functions that take a callback as a parameter. Example:

// db_helper.js
module.exports.isUserAuthenticated = function(query, callback) {
 [db code here]
 callback(err, rows);
};

And then in your routes file:

// app.js
var db_helper = require('./path/to/db_helper.js');
....
app.post('/login', function(req, res) {
 var query = [parse from request object]
 db_helper.isUserAuthenticated(query, function(err, rows) {
 if (rows.length == 1) {
 [...]
 res.render(...);
 } else {
 [...]
 res.render(...);
 }
 });
});

Node-style callbacks typically have an error as the first parameter (null if there was no error), and associated data in other parameters.

Nesting callbacks can be a pain if this gets more complicated, so I suggest you look into Promises or async

answered Jul 7, 2017 at 0:54
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You're welcome. I highly suggest looking into async since it can streamline your db_helper.js a lot. \$\endgroup\$ Commented Jul 7, 2017 at 19:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.