0

I have two set of commands that I want to run sequentially first is the database seed and the second is the actual server start but for some reason nodejs doesnot run the second command let me show you the script

package.json

 "scripts": {
    "start": "ts-node src/seeder/seedCompanies  && ts-node-dev --respawn src/index.ts"
  }

the first command is the seed the code for that is

seedCompanies.ts

import { Company } from "../entity/Company";
import { Product } from "../entity/Product";
import { ProductColor } from "../entity/ProductColor";
import { ProductSize } from "../entity/ProductSize";

import { createConnection } from "typeorm";
import bcrypt from "bcryptjs";

createConnection().then((connection): Promise<void> => {

  for (let i = 0; i <= 1; i++) {

    let company = new Company();
    company.name = `Company ${Math.random().toString(36).substring(4)}`,
      company.email = `email${Math.random().toString(36).substring(4)}@gmail.com`,
      company.address = "Demo Address",
      company.password = bcrypt.hashSync('123', 10),
      company.website = "website.com"

    connection.manager
      .save(company)
      .then(company => {


        for (let j = 0; j < 10; j++) {
          let product = new Product();
          //randon name for product as seeder will run on every server start
          product.name = `Product ${Math.random().toString(36).substring(5)}`;
          product.description = "Seed product";
          product.image = "https://picsum.photos/200/300";
          product.company = <any>company.id;
          connection.manager
            .save(product).then(product => {
              let productColor = new ProductColor();
              productColor.color = "#000";
              productColor.product = <any>product.id


              connection.manager
                .save(productColor)

              let productSize = new ProductSize();
              productSize.size = "XL";
              productSize.product = <any>product.id

              connection.manager
                .save(productSize)
            })

        }
      });
  }
  return <any>null;
})

now the seeding works great I can see the data added but the problem is nodejs is stuck at the end of this script doesnot show any error

query: SELECT `ProductSize`.`id` AS `ProductSize_id`, `ProductSize`.`size` AS `ProductSize_size` FROM `product_size` `ProductSize` WHERE `ProductSize`.`id` = ? -- PARAMETERS: [60]
query: COMMIT
query: COMMIT
query: COMMIT

these are the last lines in the terminal i tried using

process.exit(1)

but that closes the server how can i move to the next thread/command in package.json?

uneeb meer
  • 596
  • 3
  • 14
  • It's not entirely clear what you are trying to do. Do you need `seedCompanies` to continue running, while you are running the second command? And what's with the SQL Commands? where did you try to execute those? – derpirscher Jan 10 '21 at 15:12
  • No, so the seedCompanies should exist after the threads are complete – uneeb meer Jan 10 '21 at 15:18
  • Does this answer your question? ['&&' vs. '&' with the 'test' command in Bash](https://stackoverflow.com/questions/26770568/vs-with-the-test-command-in-bash) – derpirscher Jan 10 '21 at 15:19

1 Answers1

1

The NPM script shows:

...: "ts-node src/seeder/seedCompanies  && ts-node-dev --respawn ..."

The && there is indicating "only run the next command if the previous command exits successfully". To do that from Node process, you would call process.exit with 0 not 1. See here for some details on exit codes.

You need to specify in your seedCompanies script when the seeding was successful or failed. Something like:

createConnection()
.then((connection): Promise<any> => {
  // Use the connection, waiting for it to finish
  // See below for comments!
}).then(() => {
  // Seeding successful
  return process.exit(0);
})
.catch((err): Promise<any> => {
    // Seeding Failed
    return process.exit(1);
});

Note that in your example code you're not waiting for the promise chain inside of the for ... loop to complete. You'll need to do that appropriately to make sure the data is finished seeding before exiting. If you need help there, it's probably a different question.

Peter Wagener
  • 1,928
  • 12
  • 19
  • well that does work but now the seeding doesnt maybe it exists out right away? – uneeb meer Jan 10 '21 at 15:17
  • @uneebmeer of course it does. `process.exit` does as its name suggests. it exits (ie stops) the process. – derpirscher Jan 10 '21 at 15:18
  • Probably so. As mentioned, If you aren't waiting for the promises inside the `for ...` loop to complete, then node will exit immediately. Promises can be tricky. – Peter Wagener Jan 10 '21 at 15:19
  • how to make it wait for the process to complete then exit out? – uneeb meer Jan 10 '21 at 15:20
  • There are lots of other answers to waiting for promises generated by a `for ...` loop. For instance: https://stackoverflow.com/questions/31426740/how-to-return-many-promises-and-wait-for-them-all-before-doing-other-stuff . If that doesn't help, feel free to post a different question & link it in a comment here. – Peter Wagener Jan 10 '21 at 15:34
  • @PeterWagener thanks for the tip it worked perfectly fine had to add bunch of async/awaits.Keep up the good work!!! – uneeb meer Jan 10 '21 at 15:45