Patrick
Patrick

Reputation: 3172

How to return results from MySQL in HAPI

I'm new to Node and HAPI and am working through tutorials on a basic CRUD API.

I am trying to do a simple SQL query to retrieve a few rows out of the database and return the data in the request.

// routes.js
'use strict';
const Path = require('path');
const dbconn = require('./models');
const Home = require ('./controllers/home');

module.exports = [
    {
        method: 'GET',
        path: '/',
        handler: Home,
        config: {
            description: 'Gets all the notes available'
        }
    },

];

// models.js
var db = require('mysql');

const db_name = 'nodejstest';
const db_user = 'nodejstest';
const db_pass = 'n0dejstest()';
const db_host = 'localhost';

var dbconn = db.createConnection({
    host: db_host,
    user: db_user,
    password: db_pass,
    database: db_name
});

dbconn.connect(function(err) {
    if (err) {
        console.error('[mysql error]' + err.stack);
        return;
    }
});


module.exports = dbconn;

// home.js

'use strict';

const dbconn = require('../models');

function getAllNotes(callback) {
    dbconn.query('SELECT * FROM note', [], function (err, results) {
        if (err) {
            throw err;
        }

        console.log(results);

        return callback(results);
    })
}

module.exports = async (request, h) => {
    return getAllNotes(function(results) {
        return {
            data: {
                notes: results
            },
            page: 'Home -- Notes Board',
            description: 'Welcome to my Notes Board'
        };

    })
    
}

In the console.log I am seeing the database results get logged correctly, so I know the db is returning what is expected but I cannot figure out how to get Hapi to wait until there are results from the db.

I'm on Node v12.18.1 & HAPI 19.1.1

Upvotes: 1

Views: 1081

Answers (1)

ivanph
ivanph

Reputation: 86

Your async function in Home is not returning the values from the callback. You are returning the result of calling getAllNotes which is undefined. You seem confused about how callbacks and async/promises work. You have to wrap the wrap the callback to the query in a Promise.

function getAllNotes() {
  return new Promise((resolve, reject) => {
    dbconn.query('SELECT * FROM note', [], function (err, results) {
      if (err) {
        return reject(error)
      }

      console.log(results);

      return resolve(results);
    })
  })
}

module.exports = async (request, h) => {
  // maybe add some error handling here
  const results = await getAllNotes();
  return {
    data: {
      notes: results
    },
    page: 'Home -- Notes Board',
    description: 'Welcome to my Notes Board'
  };
}

Upvotes: 2

Related Questions