How to use Nest JS with Prisma?
Published: 2024-06-04 05:57:54

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**:
   ```bash
   npm install -g @nestjs/cli
   ```

2. **Create a New Project**:
   ```bash
   nest new project-name
   cd project-name
   ```

### Step 2: Install Prisma and Generate Client
1. **Install Prisma CLI**:
   ```bash
   npm install @prisma/cli --save-dev
   ```

2. **Initialize Prisma**:
   ```bash
   npx prisma init
   ```

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

3. **Edit the `.env` file**:
   Configure your database connection in the `.env` file. For example, for a PostgreSQL database:
   ```plaintext
   DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
   ```

4. **Define your data model**:
   Edit `prisma/schema.prisma` to define your data model. For example:
   ```prisma
   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
   }
   ```

5. **Generate the Prisma Client**:
   ```bash
   npx prisma generate
   ```

### Step 3: Install and Configure Prisma in NestJS
1. **Install Prisma Client and Dependencies**:
   ```bash
   npm install @prisma/client
   npm install @nestjs/config
   ```

2. **Create a Prisma Module**:
   Create a `prisma` directory inside `src` and add `prisma.service.ts` and `prisma.module.ts` files.

3. **Prisma Service**:
   Create `src/prisma/prisma.service.ts`:
   ```typescript
   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();
     }
   }
   ```

4. **Prisma Module**:
   Create `src/prisma/prisma.module.ts`:
   ```typescript
   import { Module } from '@nestjs/common';
   import { PrismaService } from './prisma.service';

   @Module({
     providers: [PrismaService],
     exports: [PrismaService],
   })
   export class PrismaModule {}
   ```

### Step 4: Create a User Module
1. **Generate User Module, Controller, and Service**:
   ```bash
   nest g module user
   nest g controller user
   nest g service user
   ```

2. **Update User Service**:
   Open `src/user/user.service.ts` and use Prisma to interact with the database:
   ```typescript
   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 } });
     }
   }
   ```

3. **Update User Controller**:
   Open `src/user/user.controller.ts` and define the endpoints:
   ```typescript
   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);
     }
   }
   ```

4. **Update User Module**:
   Open `src/user/user.module.ts` and import the PrismaModule:
   ```typescript
   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 {}
   ```

### Step 5: Integrate User Module into App Module
1. **Update App Module**:
   Open `src/app.module.ts` and import the UserModule and PrismaModule:
   ```typescript
   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 {}
   ```

### Step 6: Run the Application
1. **Start the NestJS Application**:
   ```bash
   npm run start:dev
   ```

### 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.
     ```json
     {
       "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.

Disclaimer: This content is generated by AI.