1

I am trying to include the status of my MySQL server in the Response of my router.

health.js:

var express = require('express');
var router = express.Router();
const db = require('../database');

/* GET home page. */
router.get('/', async function(req, res, next) {
    var status = "nothing here yet";
    await db.ping((err) => {
        // Not working
        if(err) status = "Server is down!";
        status = "MySQL Server is Active";

        // Working
        //if(err) return res.status(503).send("Server down!")
        //return res.status(200).send("Server up and running!")
    })

    res.status(200).send(status);
});

module.exports = router;

database.js:

const mysql = require('mysql2');

module.exports = mysql.createConnection({
    host: 'localhost',
    user: 'testdb_user',
    password: 'test'
    database: 'testdb'
});

Accessing the route with the code above always return "nothing here yet" instead of the actual status of the database.

Using the commented code inside the db.ping() function I get the correct result that the server is either up or down.

I assume that I somehow messed it up with the concept of async/await but I'm unsure. There als also no example that I found on using the db.ping() call to set a variable that I can then use outside the function (like status in my case). How do I need to change my code above in the health.js to ensure that I can properly set my status variable and then later pass it as response?

Fabian
  • 541
  • 9
  • 30
  • 3
    Looks like ping is callback based, not promise, so awaiting it won't do what you expect. – Phix Nov 14 '21 at 20:52

1 Answers1

0

you can use npm package mysql2/promise,this package convert most mysql2 methods to promise

import mysql from 'mysql2/promise'