1

I am writing some database middleware for some expressjs app that is based on sqlite3. This is my directory structure:

     | app
       | database
          index.js
       | routes
          index.js

database/index.js contains:

module.exports.getLinkById = function(id) {
    Database.get(`SELECT redir FROM root WHERE id = "${id}"`, [], function(err, rows) {
        try {
            var row = rows;
            console.log(row.redir); // successfully logs the redir attr with correct value
            return row;
        } catch (e) {
            throw e;
        }
    });
};

and routes/index.js contains:

var database = require('../database');
console.log(database.getLinkById("afb8")); // undefined

In the database/index.js file, the row based on the id is selected and returned. For debugging, I console.log()ged it and that logs the correct value. However, even thought I returned the row value, routes/index.js treats it as undefined. How do I correctly return the value so I can access it in routes/index.js?

HackaTunes
  • 69
  • 7
  • That is somewhat what I exactly needed but I am not capable enough to know how to implement it in my case. Can you share a snippet with me? – HackaTunes May 29 '21 at 07:18

1 Answers1

3

It's an async function that does not return anything.

Simply return a response for express:

app.get("/api/user/:id", (req, res, next) => {
    var sql = "select * from user where id = ?"
    var params = [req.params.id]
    db.get(sql, params, (err, row) => {
        if (err) {
          res.status(400).json({"error":err.message});
          return;
        }
        res.json({
            "message":"success",
            "data":row
        })
      });
});

If you need to run more code alongside it, see: sqlite3 nodejs get value from table

Middleware required function, added to database.js:

// Hack to look like node-postgres
// (and handle async / await operation)
db.query = function (sql, params) {
  var that = this;
  return new Promise(function (resolve, reject) {
    that.all(sql, params, function (error, rows) {
      if (error)
        reject(error);
      else
        resolve({ rows: rows });
    });
  });
};
Chris Chan
  • 63
  • 3
  • Obviously I can do that but how do I implement it in middleware? – HackaTunes May 29 '21 at 07:24
  • 2
    @HackaTunes Unfortunately, sqlite3 doesn't support native async await support, if you need to have a middeware, it has to do async await. Please find a full working example below. You can scroll all the way down. I also updated my answer to include the most important part of code. https://blog.pagesd.info/2019/10/29/use-sqlite-node-async-await/ – Chris Chan May 29 '21 at 07:31