0
respostas

Erro ao criar a infraestrutura

Olá,

Estou a tentar fazer extender um pouco o curso e estou a tentar criar uma infraestrutura que faça o DROP, CREATE das tabelas e o INSERT dos registos

class DropTables {
  async init(connection) {
    this.connection = connection;

    //DROP
    await this.dropPrivileges();

  }
    async dropPrivileges() {
    const sql = 'DROP TABLE IF EXISTS privileges';
    this.connection.query(sql, (error) => {
      if (error) {
        console.log(error);
      } else {
        console.log('>>> Privileges Table was successfully dropped');
      }
    });
  };
 }
class CreateTables {
  async init(connection) {
    this.connection = connection;

    //CREATE
    await this.createPrivileges();

  }
    async createPrivileges() {
    const sql = 'CREATE TABLE IF NOT EXISTS privileges (privilegeId INT NOT NULL AUTO_INCREMENT, description VARCHAR(45) NOT NULL, PRIMARY KEY (privilegeId))';
    this.connection.query(sql, (error) => {
      if (error) {
        console.log(error);
      } else {
        console.log('>>> Privileges Table was successfully created');
      }
    });
  };
 }
class InsertRecords {
  async init(connection) {
    this.connection = connection;

    await this.insertsList();

  }
    async insertPrivileges() {
    const insertsList = [
      "INSERT INTO privileges (privilegeId, description) VALUES (1, 'cc_admin')",
      "INSERT INTO privileges (privilegeId, description) VALUES (2, 'cc_user')"
    ];
    for (let i = 0; i < insertsList.length; i++) {
      let sql = insertsList[i];
      this.connection.query(sql, (error) => {
        if (error) {
          console.log(error);
        }
      });
    }
    console.log('>>> Privileges inserts completed');
  };
 }

Depois adicionei-os no "index.js" para serem chamados

  const customExpress = require('./config/customExpress');
  const connection = require('./infrastructure/connection');
  const DropTables = require('./infrastructure/dropTables');
  const CreateTables = require('./infrastructure/createTables');
  const InsertRecords = require('./infrastructure/insertRecords');

  connection.connect(async error => {
    if (error) {
      console.log(error);
    } else {
      //sucesso na ligação à base de dados
      console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
      console.log(">>> Successfully connected to the database");

      await DropTables.init(connection);
      await CreateTables.init(connection);
      await InsertRecords.init(connection);

      //carregar as configurações
      const app = customExpress();

      app.listen(3000, () => console.log('>>> Server started at port 3000'));

    }
  });

Seguidamente executo o comando "npm start" para iniciar a API

D:\xampp\htdocs\costcontrol_backend>npm start

> costcontrol@1.0.0 start D:\xampp\htdocs\costcontrol_backend
> nodemon index.js

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json  
[nodemon] starting `node index.js`
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>> Successfully connected to the database
>>> Privileges inserts completed
consign v0.1.6 Initialized in D:\xampp\htdocs\costcontrol_backend
+ .\controllers\privileges.js
>>> Server started at port 3000
>>> Privileges Table was successfully dropped
>>> Privileges Table was successfully created

E como podem ver no log, aparentemente o "INSERT" é executado antes do "DROP" e do "CREATE". Mas quando vamos à base de dados os registos estão lá. Já tentei usar promises (async e await) e mesmo assim não consigo colocar por ordem. Estou a fazer alguma coisa mal ?

Desde já muito obrigado,