node.jssequelize.jssequelize-cli

Running Sequelize Migration and Node Server in Same Command Won't Start Server Up


If I try to run my sequelize migrations and then run my Node server in the same command, I run into the issue of my server never starting up. If the migrations have already been run before, the sequelize db:migrate command doesn't go past the "No migrations were executed, database schema was already up to date." message, and my second command is never able to run. If the migration has not run before, everything runs properly in sequence.

This is my npm start command: sequelize db:migrate && node index.js

I assume that internally sequelize db:migrate is not resolving anything in the case where this log message is shown, so is there a way I can "terminate" this command after some time and proceed to my node command?


Solution

  • For anyone else running into this issue, this is how I ended up solving it.

    1) Create a new file that you will run in your npm script.

    2) I ended up wrapping the process call in a child_process exec, and then terminated the process when I received the above console.log message since the library itself does not resolve anything at this point.

    // myRuntimeFile.js --> Make sure this file is in the same directory where your .sequelizerc file lives
    
    (async()=> {
      const { exec } = require('child_process');
    
      await new Promise((resolve, reject) => {
        const migrate = exec(
          'sequelize db:migrate',
          { env: process.env },
          (err, stdout, stderr) => {
            resolve();
          }
        );
    
        // Listen for the console.log message and kill the process to proceed to the next step in the npm script
        migrate.stdout.on('data', (data) => {
          console.log(data);
          if (data.indexOf('No migrations were executed, database schema was already up to date.') !== -1) {
            migrate.kill();
          }
        });
      });
    })();
    

    Obviously the above code is not ideal, but hopefully this is just temporary until the internals of this edge case are resolved properly in a promise.

    3) Update your npm script with the following:

    "start": "node myRuntimeFile.js && node index.js"

    Or if you are running on a Windows machine and cannot use &&, you can use the npm-run-all library.