using-prisma-orm-to-manage-mysql-databases-in-a-nestjs-project.html

Using Prisma ORM to Manage MySQL Databases in a NestJS Project

When developing modern web applications, managing databases efficiently is paramount. In the world of Node.js, Prisma ORM has emerged as a powerful tool for database management due to its type-safe querying capabilities and seamless integration with popular frameworks like NestJS. In this article, we’ll delve into using Prisma ORM to manage MySQL databases within a NestJS project. We’ll cover the setup process, key features, and actionable insights that will enhance your development experience.

What is Prisma ORM?

Prisma ORM is an open-source database toolkit that simplifies database interactions. It abstracts the complexities of database queries, allowing developers to focus on writing business logic instead of dealing with raw SQL. Prisma provides a type-safe API, making it easier to work with databases without running into common pitfalls associated with SQL queries.

Key Features of Prisma ORM

  • Type Safety: Automatic type generation based on your database schema.
  • Query Optimization: Efficiently fetch data with minimal database queries.
  • Migration System: Smooth management of database schema changes.
  • Multi-Database Support: Works with MySQL, PostgreSQL, SQLite, and more.

Setting Up Prisma with NestJS

Step 1: Create a New NestJS Project

First, ensure you have Node.js and Nest CLI installed. If not, you can install them using npm:

npm install -g @nestjs/cli

Now, create a new NestJS project:

nest new my-nest-prisma-app
cd my-nest-prisma-app

Step 2: Install Prisma and MySQL Dependencies

Next, you’ll need to install Prisma and the MySQL database driver. Run the following command:

npm install prisma --save-dev
npm install @prisma/client mysql2

Step 3: Initialize Prisma

Now that you have Prisma installed, initialize it in your project:

npx prisma init

This command creates a prisma folder with a schema.prisma file, where you’ll define your database schema.

Step 4: Configure the Database Connection

Open the schema.prisma file and configure your MySQL database connection:

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

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

Make sure to set the DATABASE_URL environment variable in your .env file:

DATABASE_URL="mysql://USER:PASSWORD@localhost:3306/DATABASE_NAME"

Replace USER, PASSWORD, and DATABASE_NAME with your actual MySQL credentials.

Step 5: Define Your Models

In the schema.prisma file, define your data models. Here’s an example of a simple User model:

model User {
  id    Int    @id @default(autoincrement())
  name  String
  email String @unique
  age   Int?
}

Step 6: Generate the Prisma Client

After defining your models, run the following command to generate the Prisma Client:

npx prisma generate

This command creates a type-safe client that you can use to interact with your database.

Using Prisma in Your NestJS Application

Step 7: Create a User Module

Create a User module that will handle user-related operations. Generate the module and service using the Nest CLI:

nest generate module users
nest generate service users

Step 8: Implement CRUD Operations

Open the users.service.ts file and implement CRUD operations using Prisma Client.

import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { User } from '@prisma/client';

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

  async createUser(data: { name: string; email: string; age?: number }): Promise<User> {
    return this.prisma.user.create({ data });
  }

  async getAllUsers(): Promise<User[]> {
    return this.prisma.user.findMany();
  }

  async getUserById(id: number): Promise<User | null> {
    return this.prisma.user.findUnique({ where: { id } });
  }

  async updateUser(id: number, data: Partial<{ name: string; email: string; age?: number }>): Promise<User> {
    return this.prisma.user.update({ where: { id }, data });
  }

  async deleteUser(id: number): Promise<User> {
    return this.prisma.user.delete({ where: { id } });
  }
}

Step 9: Set Up PrismaService

Create a prisma.service.ts file to encapsulate the Prisma Client.

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

@Injectable()
export class PrismaService extends PrismaClient {
  constructor() {
    super();
  }
}

Step 10: Integrate PrismaService into Your Module

Finally, integrate the PrismaService in your app's module, typically app.module.ts.

import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { PrismaService } from './prisma/prisma.service';

@Module({
  imports: [UsersModule],
  providers: [PrismaService],
})
export class AppModule {}

Conclusion

Using Prisma ORM with NestJS to manage MySQL databases allows you to build robust applications with a clean, type-safe API. By following the steps outlined in this article, you can set up a complete CRUD application, enabling you to focus on delivering value through your business logic rather than boilerplate code.

As you continue to explore the capabilities of Prisma and NestJS, consider leveraging advanced features like middleware, transactions, and query optimizations to further enhance your application's performance. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.