#TypeScript NodeJS MariaDB (Vite) No Error Help

9 messages · Page 1 of 1 (latest)

bronze breach
#

The code below simply wont work and doesn't output an error. I want to take an object/array such as 'structures' below and convert it automatically into a table if the table does not already exist in the db.

import mariadb from 'mariadb';

const pool = mariadb.createPool({
     host: '-----------------', 
     user: 'react',
     password: '-----------',
     database: 'react',
     connectionLimit: 5
});

let structure = {
     Users: {username: 'TEXT', password: 'TEXT'}
}

async function main() {
     try {
          let conn
          
          Object.keys(structure).forEach(async (tableData, tableName) => {
               let i = 0
               let columns = ''
               Object.keys(tableData).forEach((columnType, column) => {
                    i = i + 1
                    if (i > 0) {
                         columns = columns + ', ' + column + ' ' + columnType
                    } else {
                         columns = columns + column + ' ' + columnType
                    }
               });
               
               if (columns.length > 5) {
                    conn = await fetchConn()
                    .then(conn => {
                         conn.query('CREATE TABLE IF NOT EXISTS ' + tableName + ' (' + columns + ');')
                         .then((res) => {
                              console.log(res);
                              conn.end();
                         })
                         .catch(err => {
                              console.log(err); 
                              conn.end();
                         })
                    });
               }
          });

          console.log("Total connections: ", pool.totalConnections());
          console.log("Active connections: ", pool.activeConnections());
          console.log("Idle connections: ", pool.idleConnections());
     } catch (err) {
          console.log(err);
     }
}
// more code
#

async function fetchConn() {
     let conn = await pool.getConnection();
     console.log("Total connections: ", pool.totalConnections());
     console.log("Active connections: ", pool.activeConnections());
     console.log("Idle connections: ", pool.idleConnections());
     return conn;
}
main();

export default pool
export {
     fetchConn
}
#

using Vite

#

TypeScript NodeJS MariaDB (Vite) No Error Help

keen ingot
#

forEach isn't going to await the returns

#

even when passing in an async callback

#

hmm looking closer i don't think that's it actually

#

you're not doing anything with the async function's return value anyway

#

although you're overwriting conn every time it's set almost immediately