Search code examples
node.jssqliteasync-awaitkoa

koa and sqlite3 node REST endpoint returning only Database object instead of data


I have a simple GET route setup with Koa and sql3lite that fetches from a json file some data, with the use of a wrapper.

A helper sql3lite wrapper exposes an initialize function for the main server index.js file to load into memory on startup:

index.js

const data = require('./data');

data.initialize();

const server = createServer();

server.listen(PORT, () => {
  console.log(`server listening on port ${PORT}`);
});

The data.js file serves as a wrapper around the sqlite3 node library, so routes can call the connection() method individually.

data.js

const connection = new sqlite3.Database(':memory:');

function initialize() {
  connection.serialize(() => {
    connection.run('CREATE TABLE meter_reads (cumulative INTEGER, reading_date STRING, unit STRING)');

    const { electricity } = sampleData;
    electricity.forEach((data) => {
      connection.run(
        'INSERT INTO meter_reads (cumulative, reading_date, unit) VALUES (?, ?, ?)',
        [data.cumulative, data.readingDate, data.unit],
      );
    });
  });
}

module.exports = {
  initialize,
  connection,
}; 

The problem I am having is sending the data object back to a client or postman when calling the exported connection method:

koa route

const db = require('../data');
router.get('/meter/readings', async (ctx, next) => {
  ctx.body = await db.connection.all('SELECT * FROM meter_reads', (err, data) => data);
});

GET request to route result: { "open": true, "filename": ":memory:", "mode": 65542 }

Interesting quirk:

By wrapping the data object, produced by the db.connection.all() method above with console.log(), I can print out the expected data on the node server. It's almost like ctx.body is screwing up something. I've been an express guy up until now so apologies if this is a rookie mistake!


Solution

  • Answered by GMS here: https://github.com/mapbox/node-sqlite3/issues/1046#issuecomment-425643910

    'all' does not return any value ( it returns the result by calling the given callback) so you are actually awaiting 'db.connection' in this line of code there are some libraries based on node-sqlite3 providing promise based API and more e.g https://www.npmjs.com/package/sqlite or mine: https://www.npmjs.com/package/sqlite3orm