Building a REST API with Prisma and express.js

Defining table relations

Now that we defined both collections for the users and the games, it’s now time to define the relationships between them.

As mentioned before, we want a user to be able to have multiple games, and we also don’t want duplicate game entries so we want a game to be associated with multiple users as well.

Let’s define the relationships.

We just need to add two more lines of code in the schema.

prisma models

Now that we have defined our schemas, it’s time to make these changes in the Postgres database as well, because this schema is nothing but a piece of code, we’ll have to tell Prisma to take these schemas and make these changes in the database as well.

For that Prisma has provided us with a command.

In the root directory of your application run npx prisma migrate dev this will make the changes to your database and migrate the changes. The migrations will be put into the folder prisma/migrations

If you encounter errors when running this command, make sure that Postgres is installed properly on your computer and the username and password that you put inside the .env file are correct.

Now our database is completely in sync with our Prisma schema, there is another command that we need to run, this one is for TypeScript it will create the types using the Prisma schema so that your application will be completely type-safe.

For that run npx prisma generate this will generate the TypeScript defenitions inside the .\node_modules\@prisma\client folder.

Now our TypeScript definitions have been created, it’s time to use the Prisma client so that we can run queries.

Create a file called prisma.ts or client.ts and write the following code.

import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient()

export default prisma

We will now import this instance into other places of our code to do database queries.