// testing : 
// https://mariadb.com/kb/en/nodejs-connector/

const http  = require ('http');  // to create server
const url   = require('url');    // to parse url
const BASIC_API_PORT = 3998;

const DB_HOST = "127.0.0.1",
      DB_PORT = "3306",
      DB_USR  = "nodeapi", 
      DB_PWD  = "RDSGF435FG",
      DB_NAME = "nodeapi";
const mariadb = require('mariadb');

const pool = mariadb.createPool({
 host: DB_HOST,
 port: DB_PORT,
 user: DB_USR,
 password:DB_PWD,
 database: DB_NAME,
 connectionLimit: 5,
});

//const server = http.createServer(function (req, resp) {
const app = http.createServer
(
    async (req, res) =>
    {
        const parsedURL = url.parse(req.url, true);
        var response_text = "";
        if(req.method === 'GET' && parsedURL.pathname.startsWith('/api/tables'))
        {
            console.log('requesting table list');
            var cnx = null;
            try
            {
                cnx=await pool.getConnection();
                const tables_res = await cnx.query("SHOW TABLES");
                console.log(tables_res);
                response_text += tables_res.length+" table"+(tables_res.length>1?"s":"")+" found";
                //console.log(response_text);
                if(tables_res.length > 0)
                {
                    Object.keys(tables_res).forEach(function(key) {
                            if(key !== 'meta')
                            {
                                var row=tables_res[key];
                                response_text+= "\n - "+row['Tables_in_'+DB_NAME];
                            }
                    });
                }

            }
            catch(err)
            {
                throw(err);
            }
            finally
            {
                    res.statusCode = 200;
                    res.end(response_text);
                    if(cnx)
                    { 
                        return cnx.end(); 
                    }
            }
        }
        else
        {
            res.statusCode = 400;
            res.end("API Endpoint Not Supported");
        }
    }
);
app.listen(BASIC_API_PORT);
console.log('mariadb test api started');

      
      
