Database Integration: Persisting Data
10 min read
Database Integration: Persisting Data πΎ
Welcome back! So far, our NestJS application has been living in a world of temporary memory. Every time we restart it, any data it was holding onto vanishes into the digital ether. It's like having a brilliant conversation with a goldfish β entertaining, but with zero long-term recall. To build truly useful applications, we need a way to store data permanently. That's where databases come in, and this guide will walk you through integrating one into your NestJS project.
This is a crucial step in building real-world applications. Think about it β what's a social media app without user accounts? An e-commerce site without products? A to-do list that forgets everything when you close the browser? Pretty useless, right? By the end of this guide, you'll have the power to give your application a long-term memory.
Choosing an ORM: TypeORM vs Prisma in NestJS
Before we can start storing data, we need to decide how we're going to talk to our database. We could write raw SQL queries, but that can get messy and error-prone, especially as our application grows. Imagine manually writing INSERT, UPDATE, and DELETE statements for every little change. It's like trying to build a skyscraper with a hand-saw β possible, but incredibly inefficient and likely to end in disaster.
This is the problem that Object-Relational Mappers (ORMs) solve. An ORM is a library that creates a "bridge" between the object-oriented world of your code (like TypeScript classes) and the relational world of a SQL database. It lets you interact with your database tables as if they were regular objects, saving you from the tedious and often repetitive task of writing SQL.
In the NestJS ecosystem, two ORMs stand out: TypeORM and Prisma.
π€Ό TypeORM vs. Prisma: A Friendly Showdown
Choosing between TypeORM and Prisma is a common dilemma for NestJS developers. Both are excellent tools, but they have different philosophies and strengths. Let's break them down.
TypeORM
Think of TypeORM as the seasoned veteran. It's been around for a while and is the most mature ORM for TypeScript. It follows the traditional "decorator-based" approach, where you define your database entities using classes and decorators.
Key Features:
- Decorator-Based Entities: You define your database tables using TypeScript classes and decorators like
@Entity(),@Column(), and@PrimaryGeneratedColumn(). This feels very natural within a NestJS application. - Repository Pattern: TypeORM embraces the repository design pattern, providing a dedicated object for each entity to handle database operations.
- Powerful Query Builder: For complex queries that go beyond simple CRUD operations, TypeORM offers a flexible and powerful query builder.
- Mature and Stable: As the long-standing choice, it has a large community and a wealth of resources available.
A little exaggeration: Using TypeORM is like hiring a very experienced, slightly old-fashioned butler. He knows all the proper etiquette for interacting with the database and will handle most tasks with grace and precision.
Prisma
Prisma is the modern, trendy newcomer. It takes a different approach by using a schema-first workflow. You define your data model in a special schema.prisma file, and Prisma generates a type-safe client for you to interact with your database.
Key Features:
- Schema-First Approach: You define your database models in a dedicated
.prismafile. This provides a single source of truth for your database schema. - Type-Safe Client: Prisma generates a highly type-safe client that makes it difficult to write queries that are invalid at runtime. This is a huge win for developer productivity and bug prevention.
- Excellent Tooling: Prisma comes with a fantastic set of tools, including a powerful migration system and a visual database browser (Prisma Studio).
- Growing Popularity: Prisma has been gaining a lot of traction in the Node.js community for its developer-friendly experience.
A little exaggeration: Prisma is like having a hyper-intelligent, slightly futuristic robot assistant. It anticipates your needs, prevents you from making mistakes, and has a sleek, modern interface.
So, which one should you choose?
For beginners, Prisma's guided workflow and excellent type safety can make the initial learning curve a bit smoother. TypeORM, on the other hand, might feel more familiar to developers with a background in other popular ORMs like Hibernate or Entity Framework.
Ultimately, the best choice depends on your team's preferences and the specific needs of your project. For this guide, we'll provide examples for both!
Connecting to a Database and Configuring Modules
Alright, decision time is over! Now let's get our hands dirty and actually connect our NestJS application to a database. The process is similar for both TypeORM and Prisma, involving installing the necessary packages and configuring a module.
π§ With TypeORM
First, you'll need to install the required dependencies. For this example, we'll use PostgreSQL, a popular and powerful open-source relational database.
npm install --save @nestjs/typeorm typeorm pgThis command installs the NestJS TypeORM package, TypeORM itself, and the pg driver for PostgreSQL.
Next, we need to configure the TypeOrmModule in our app.module.ts. This is where we tell NestJS how to connect to our database.
// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { User } from './user/user.entity'; // We'll create this soon!
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'your_username',
password: 'your_password',
database: 'your_database',
entities: [User],
synchronize: true, // β οΈ Don't use in production!
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}A very important note: The synchronize: true option is great for development as it automatically updates your database schema to match your entities. However, you should never use it in production, as it can lead to data loss. In a production environment, you should use migrations to manage schema changes.
π§ With Prisma
For Prisma, the setup is a bit different. First, install the Prisma CLI as a development dependency:
npm install prisma --save-devNow, initialize Prisma in your project:
npx prisma initThis command creates a new prisma directory with a schema.prisma file and a .env file for your database credentials.
Open your .env file and set the DATABASE_URL:
DATABASE_URL="postgresql://your_username:your_password@localhost:5432/your_database"Next, open prisma/schema.prisma and define your data source and a generator for the Prisma Client:
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// We'll define our models here laterNow, you need to install the Prisma Client:
npm install @prisma/clientTo make the Prisma Client available throughout your application via dependency injection, it's a good practice to create a PrismaService:
// src/prisma/prisma.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
}And a corresponding PrismaModule:
// src/prisma/prisma.module.ts
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}Finally, import the PrismaModule into your app.module.ts:
// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaModule } from './prisma/prisma.module';
@Module({
imports: [PrismaModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}Phew! That was a bit more involved, but now you have a robust setup for using Prisma in your NestJS application.
Defining Entities, Models, and Schemas
Now that we're connected to the database, it's time to define the structure of our data. This is where we create the "blueprints" for our database tables.
π With TypeORM: Entities
In TypeORM, you define entities as TypeScript classes with decorators. Let's create a simple User entity.
// src/user/user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ default: true })
isActive: boolean;
}Here's what's happening:
@Entity(): This decorator marks theUserclass as a database entity.@PrimaryGeneratedColumn(): This specifies that theidproperty is the primary key and its value will be automatically generated.@Column(): This decorator maps a class property to a column in the database table.
Don't forget to add this new entity to the entities array in your TypeOrmModule.forRoot() configuration.
π With Prisma: Models
With Prisma, you define your models in the schema.prisma file using Prisma's schema language.
// prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
firstName String?
lastName String?
isActive Boolean @default(true)
}Here's the breakdown:
model User: This defines a new model namedUser, which will map to aUsertable in the database.@id @default(autoincrement()): This marks theidfield as the primary key and specifies that it should be an auto-incrementing integer.@unique: This ensures that every user has a unique email address.String?: The question mark indicates that this field is optional.
After defining your model, you need to run a migration to apply these changes to your database and generate the Prisma Client:
npx prisma migrate dev --name initThis command will create a new SQL migration file and update your database schema. It will also regenerate the Prisma Client to include type-safe methods for interacting with the User model.
Executing CRUD Operations via Repositories
With our database connected and our data models defined, we can finally start performing the fundamental operations of any data-driven application: Create, Read, Update, and Delete (CRUD).
π οΈ With TypeORM: Repositories
TypeORM uses the repository pattern to manage entities. To perform CRUD operations on our User entity, we first need to inject the UserRepository.
In your user.module.ts, you need to import TypeOrmModule.forFeature([User]). This makes the UserRepository available for dependency injection within this module.
// src/user/user.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService],
controllers: [UserController],
})
export class UserModule {}Now, you can inject the UserRepository into your UserService:
// src/user/user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
findAll(): Promise<User[]> {
return this.usersRepository.find();
}
findOne(id: number): Promise<User | null> {
return this.usersRepository.findOneBy({ id });
}
async create(user: Partial<User>): Promise<User> {
const newUser = this.usersRepository.create(user);
return this.usersRepository.save(newUser);
}
async update(id: number, user: Partial<User>): Promise<void> {
await this.usersRepository.update(id, user);
}
async remove(id: number): Promise<void> {
await this.usersRepository.delete(id);
}
}The Repository class provides a set of methods like find(), findOneBy(), create(), save(), update(), and delete() that make performing CRUD operations a breeze.
π οΈ With Prisma: Prisma Client
With Prisma, you interact with the database through the generated PrismaClient. We'll inject our PrismaService into the UserService.
// src/user/user.service.ts
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { User, Prisma } from '@prisma/client';
@Injectable()
export class UserService {
constructor(private prisma: PrismaService) {}
async findAll(): Promise<User[]> {
return this.prisma.user.findMany();
}
async findOne(id: number): Promise<User | null> {
return this.prisma.user.findUnique({ where: { id } });
}
async create(data: Prisma.UserCreateInput): Promise<User> {
return this.prisma.user.create({ data });
}
async update(id: number, data: Prisma.UserUpdateInput): Promise<User> {
return this.prisma.user.update({
where: { id },
data,
});
}
async remove(id: number): Promise<User> {
return this.prisma.user.delete({ where: { id } });
}
}The PrismaClient exposes methods like findMany(), findUnique(), create(), update(), and delete() that are tailored to your specific models. This provides a very intuitive and type-safe way to work with your data.
π Further Reading and References:
- NestJS Documentation:
- TypeORM Documentation: https://typeorm.io/
- Prisma Documentation: https://www.prisma.io/docs/
- Articles and Tutorials:
- Building a CRUD REST API with Nest.js and Prisma
- (NestJS-6) CRUD Operations in NestJS Using TypeORM: An E-commerce Example
- How to use Prisma ORM and Prisma Postgres with NestJS
Challenge
You are building the backend for an e-commerce platform using NestJS and TypeORM. Your task is to implement the core components for managing products.
Create the
ProductEntity: Define a TypeORM entity namedProduct. It must have the following columns:id: A primary key, automatically generated as a UUID.name: A string, cannot be null.description: A text column that can be null.price: A number representing the price with decimal precision (e.g.,10, 2).stock: An integer representing the quantity available, with a default value of 0.createdAt: A timestamp that automatically records the creation date.updatedAt: A timestamp that automatically updates on every record update.
Create the
ProductsModule: Configure a new NestJS module namedProductsModule. This module should make theProductentity's repository available for dependency injection within its scope and export theProductsServicefor use in other modules.Implement the
ProductsService: Create an injectable service namedProductsService. Inject theProductrepository into this service and implement the following asynchronous methods for full CRUD functionality:create(productData: any): Creates a new product entity from the provided data object and saves it to the database. It should return the newly saved product.findAll(): Returns an array of all products.findOne(id: string): Finds and returns a single product by itsid.update(id: string, updateData: any): Updates the product corresponding to the givenidwith the new data. It should return the result of the update operation.remove(id: string): Deletes a product by itsid. It should return the result of the delete operation.
Expected result
Your final code should consist of three correctly implemented TypeScript classes within a single file, as if they were in product.entity.ts, products.module.ts, and products.service.ts respectively.
1. Product Entity
@Entity()
export class Product {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({ type: 'text', nullable: true })
description: string;
@Column({ type: 'decimal', precision: 10, scale: 2 })
price: number;
@Column({ type: 'int', default: 0 })
stock: number;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}2. ProductsModule
@Module({
imports: [TypeOrmModule.forFeature([Product])],
providers: [ProductsService],
exports: [ProductsService],
})
export class ProductsModule {}3. ProductsService
@Injectable()
export class ProductsService {
constructor(
@InjectRepository(Product)
private productRepository: Repository<Product>,
) {}
async create(productData: any): Promise<Product> {
const newProduct = this.productRepository.create(productData);
return this.productRepository.save(newProduct);
}
async findAll(): Promise<Product[]> {
return this.productRepository.find();
}
async findOne(id: string): Promise<Product> {
return this.productRepository.findOneBy({ id });
}
async update(id: string, updateData: any): Promise<UpdateResult> {
return this.productRepository.update(id, updateData);
}
async remove(id: string): Promise<DeleteResult> {
return this.productRepository.delete(id);
}
}