Seeding

Populating the database with fake data, now done appropriately.

Let's then seed the database, now using a script, as it is the correct approach.

To perform seeding with Prisma, we should create the seed file inside the prisma folder. In it, we'll instantiate a PrismaClient.

const prisma = new PrismaClient();

The PrismaService is not used here as it belongs to the context of Nest.

The seeding will be performed inside a transaction. So, let's create the seed() function, responsible for executing it. Just like in the other case, we should be aware of problems that may occur. Finally, invoke it afterwards.

const seed = async () => {
  try {
    await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
      // seed goes here
    });

    await prisma.$disconnect();
  } catch (error) {
    console.error(error);
    await prisma.$disconnect();
    process.exit(1);
  }
};

seed();

Note that the $transaction() receives a parameter. It is a TransactionClient, which is a specific PrismaClient appropriate for transactions.

And now the actual seed. Just put it in place of the comment. Note that the orderItems and payment receive the appropriate Prisma type.

What remains is simply to run the seed

And we may then see the result with Prisma Studio, which is a very clean tool for seeing and manipulating the database.

Commit - Seeding

Last updated