How to use Nest JS with Prisma?

nadim_ch0wdhury

Nadim Chowdhury

Posted on June 4, 2024

How to use Nest JS with Prisma?

Using NestJS with Prisma is a great choice for working with databases in a type-safe manner. Here's a step-by-step guide on how to set up NestJS with Prisma:

Step 1: Set Up a New NestJS Project

  1. Install Nest CLI:
   npm install -g @nestjs/cli
Enter fullscreen mode Exit fullscreen mode
  1. Create a New Project:
   nest new project-name
   cd project-name
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Prisma and Generate Client

  1. Install Prisma CLI:
   npm install @prisma/cli --save-dev
Enter fullscreen mode Exit fullscreen mode
  1. Initialize Prisma:
   npx prisma init
Enter fullscreen mode Exit fullscreen mode

This will create a prisma directory with a schema.prisma file and a .env file.

  1. Edit the .env file: Configure your database connection in the .env file. For example, for a PostgreSQL database:
   DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
Enter fullscreen mode Exit fullscreen mode
  1. Define your data model: Edit prisma/schema.prisma to define your data model. For example:
   datasource db {
     provider = "postgresql"
     url      = env("DATABASE_URL")
   }

   generator client {
     provider = "prisma-client-js"
   }

   model User {
     id    Int     @id @default(autoincrement())
     name  String
     email String  @unique
   }
Enter fullscreen mode Exit fullscreen mode
  1. Generate the Prisma Client:
   npx prisma generate
Enter fullscreen mode Exit fullscreen mode

Step 3: Install and Configure Prisma in NestJS

  1. Install Prisma Client and Dependencies:
   npm install @prisma/client
   npm install @nestjs/config
Enter fullscreen mode Exit fullscreen mode
  1. Create a Prisma Module:
    Create a prisma directory inside src and add prisma.service.ts and prisma.module.ts files.

  2. Prisma Service:
    Create src/prisma/prisma.service.ts:

   import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
   import { PrismaClient } from '@prisma/client';

   @Injectable()
   export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
     async onModuleInit() {
       await this.$connect();
     }

     async onModuleDestroy() {
       await this.$disconnect();
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Prisma Module: Create src/prisma/prisma.module.ts:
   import { Module } from '@nestjs/common';
   import { PrismaService } from './prisma.service';

   @Module({
     providers: [PrismaService],
     exports: [PrismaService],
   })
   export class PrismaModule {}
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a User Module

  1. Generate User Module, Controller, and Service:
   nest g module user
   nest g controller user
   nest g service user
Enter fullscreen mode Exit fullscreen mode
  1. Update User Service: Open src/user/user.service.ts and use Prisma to interact with the database:
   import { Injectable } from '@nestjs/common';
   import { PrismaService } from '../prisma/prisma.service';

   @Injectable()
   export class UserService {
     constructor(private prisma: PrismaService) {}

     async getUsers() {
       return this.prisma.user.findMany();
     }

     async getUser(id: number) {
       return this.prisma.user.findUnique({ where: { id } });
     }

     async createUser(name: string, email: string) {
       return this.prisma.user.create({ data: { name, email } });
     }

     async deleteUser(id: number) {
       return this.prisma.user.delete({ where: { id } });
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Update User Controller: Open src/user/user.controller.ts and define the endpoints:
   import { Controller, Get, Param, Post, Body, Delete } from '@nestjs/common';
   import { UserService } from './user.service';

   @Controller('users')
   export class UserController {
     constructor(private userService: UserService) {}

     @Get()
     async getUsers() {
       return this.userService.getUsers();
     }

     @Get(':id')
     async getUser(@Param('id') id: number) {
       return this.userService.getUser(id);
     }

     @Post()
     async createUser(@Body('name') name: string, @Body('email') email: string) {
       return this.userService.createUser(name, email);
     }

     @Delete(':id')
     async deleteUser(@Param('id') id: number) {
       return this.userService.deleteUser(id);
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Update User Module: Open src/user/user.module.ts and import the PrismaModule:
   import { Module } from '@nestjs/common';
   import { UserService } from './user.service';
   import { UserController } from './user.controller';
   import { PrismaModule } from '../prisma/prisma.module';

   @Module({
     imports: [PrismaModule],
     providers: [UserService],
     controllers: [UserController],
   })
   export class UserModule {}
Enter fullscreen mode Exit fullscreen mode

Step 5: Integrate User Module into App Module

  1. Update App Module: Open src/app.module.ts and import the UserModule and PrismaModule:
   import { Module } from '@nestjs/common';
   import { ConfigModule } from '@nestjs/config';
   import { UserModule } from './user/user.module';
   import { PrismaModule } from './prisma/prisma.module';

   @Module({
     imports: [
       ConfigModule.forRoot({ isGlobal: true }),
       UserModule,
       PrismaModule,
     ],
   })
   export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Step 6: Run the Application

  1. Start the NestJS Application:
   npm run start:dev
Enter fullscreen mode Exit fullscreen mode

Step 7: Test the Application

  1. Test Endpoints:
    Use a tool like Postman or curl to test the RESTful API endpoints:

    • GET /users: Retrieve all users.
    • GET /users/:id: Retrieve a user by ID.
    • POST /users: Create a new user.
     {
       "name": "John Doe",
       "email": "john@example.com"
     }
    
  • DELETE /users/:id: Delete a user by ID.

This guide provides a foundational approach to integrating Prisma with a NestJS application. You can further expand and customize it based on your application's requirements.

If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!

Disclaimer: This content is generated by AI.

💖 💪 🙅 🚩
nadim_ch0wdhury
Nadim Chowdhury

Posted on June 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related