How to implement NestJS with Prisma

Gnanabillian
YavarTechWorks
Published in
5 min readOct 3, 2022

NestJS is a framework for creating scalable, server-side Node.js applications. It uses modern JavaScript, fully supports and is built using TypeScript, and combines elements of object-oriented, functional, and functional reactive programming.

This post will demonstrate how to use Nest and Prisma to build a REST API. Here’s what we’ll cover:

  • What is Prisma
  • What is Prisma used for
  • Initial project setup
  • Getting started with Prisma
  • Connecting to a database
  • Creating the database schema
  • Setting up the Prisma Client and Prisma Service
  • Generating a todo module
  • Testing our application

What is Prisma?

Prisma is a next-generation Node and TypeScript object-relational mapper (ORM). It provides an open-source database toolkit for PostgreSQL, MySQL, SQL Server, SQLite, and MongoDB (currently in preview), enabling developers to build apps faster and with fewer errors.

Prisma provides you with a declarative method for defining your app’s data models and relations in a more legible format. Plus, if you already have a database, you don’t have to go through the pain of creating database models from scratch because Prisma’s introspection features handle that for you — it’s that flexible.

What is Prisma used for?

Prisma improves type safety by simplifying database access, saving and reducing repetitive CRUD boilerplate. Prisma is easy to integrate into your preferred framework and is an ideal database toolkit for creating dependable and scalable web APIs. Prisma integrates quickly with various frameworks, such as GraphQL, Next.js, Nest, Apollo, and Express.js

Prisma addresses many shortcomings of traditional ORMs, such as a lack of type safety, mixed business and storage logic, and unpredictable queries caused by lazy loading.

Initial project setup

To get started with this tutorial, ensure you have:

  • Node.js (≥v10.13.0, except for v13) installed
  • Postman installed

Before we start building a Nest application, you need to install the Nest CLI with the command below:

npm i -g @nestjs/cli

Wait for the installation to finish. Once the installation is complete, create a new Nest application with the command below:

nest new prisma-api

Choose npm as the preferred package manager and hit Enter. The application will go through some installation processes.

Once npm has installed all the packages required to run the application, change the directory to the project folder and run the server with the command below:

npm run start:dev

Getting started with Prisma

This tutorial uses Prisma v3.11.0. Install the Prisma CLI as a development dependency with the command below:

npm install prisma -save-dev

Once the installation is finished, invoke the Prisma CLI locally using npx with the command below:

npx prisma

Now, create your initial Prisma setup using the Prisma init command:

npx prisma init

The above command creates a new Prisma directory with the following files:

  • schema.prisma: specifies your database connection and contains the database schema
  • .env: a dotenv file typically used to store your database credentials in a group of environment variables

Connecting to a database

With Prisma installed, setup on your computer is pretty easy. For the demonstration in this tutorial, we’ll connect to a PostgreSQL database. To get started, open the datasource/schema.prisma file and update the content with the code below:

In the above snippet, we specified PostgreSQL as our database provider. Now, modify the .env file to specify the location of the database file.

DATABASE_URL=”postgresql://username:password@host:port/database_name?schema=public”

Creating the database schema

With the database connection set up, you can now create your database tables by defining a schema in the schema.prisma file. For the demonstration in this tutorial, we’ll define a Todo schema, with the code below:

Generate your PostgreSQL migration files and run them against the database with the command below:

npx prisma migrate dev -name init

Setting up Prisma Client and Prisma Service

Prisma Client is a type-safe database client generated from your Prisma model definition. It exposes the CRUD operations tailored specifically to your models.

Install Prisma Client with the command below:

npm install @prisma/client

With Prisma Client set up, create a prisma.service file in the src folder to abstract away the Prisma Client API for database queries within a service with the code below:

In the above code, we created a new PrismaService that takes care of instantiating PrismaClient and connecting to your database.

Generating a todo module

With the Prisma service set up, generate a todo module for all the todo logic with the command below:

nest generate module todo

Next, generate a service file for the user module with the command below:

nest generate service todo

Then, update the content of the todo.service file with the code below:

In the above code, we’ve created all the CRUD operations for our user’s service.

Now, generate a todo controller to define all the API routes for the user service with the command below:

nest generate controller todo

Update the contents of the todo.controller.ts file with the code below:

Open the todo.module.ts file, import the PrismaService, and add it to the array of providers with the code below:

At this point, you have successfully created your Nest Prisma REST API! Now let’s test the application using Postman.

Testing our application

With all the API routes for the demo application created, launch Postman and test the endpoints.

Add todo route:

Get todo route:

Conclusion
Hope this little post will help you with many common scenarios during your application development with NestJS using Prisma.

--

--

Gnanabillian
YavarTechWorks

Software Engineer | Node.js | Javascript | Typescript | Fastify | NestJS | Sequelize | Prisma | PostgreSQL, I love open source and startups.