DEV Community

Cover image for Getting Started with NestJS and TypeORM: A Beginner's Guide
Souhail Brahmi
Souhail Brahmi

Posted on

Getting Started with NestJS and TypeORM: A Beginner's Guide

Hey everyone! 👋 If you're looking to build scalable and maintainable server-side applications with Node.js, NestJS is a fantastic framework to dive into. Combined with TypeORM for database interactions, you can create robust and type-safe applications with ease. In this guide, we'll walk through setting up a simple NestJS project with TypeORM.

Why NestJS and TypeORM?

NestJS
NestJS is a progressive Node.js framework built with TypeScript that leverages the robust features of Angular to provide a reliable structure for building server-side applications. Its modular architecture makes it easy to manage and scale large applications.

TypeORM
TypeORM is an ORM (Object-Relational Mapper) for TypeScript and JavaScript (ES7, ES6, ES5). It supports many databases and allows you to interact with your database using TypeScript's powerful type system.

Setting Up Your Environment

Prerequisites
Before we start, make sure you have Node.js and npm installed. You can download them from Node.js official website.

Step 1: Create a New NestJS Project
First, we'll create a new NestJS project using the Nest CLI. If you don't have the Nest CLI installed, you can install it globally:

npm install -g @nestjs/cli
Enter fullscreen mode Exit fullscreen mode

Now, create a new project:

nest new my-nestjs-project
Enter fullscreen mode Exit fullscreen mode

Step 2: Install TypeORM and Dependencies
Next, we need to install TypeORM and the database driver we'll use. For this example, we'll use SQLite because it's simple and doesn't require any setup.

npm install @nestjs/typeorm typeorm sqlite3
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure TypeORM
We need to configure TypeORM in our NestJS project. Open src/app.module.ts and update it to include TypeORM configuration:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'database.sqlite',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Step 4: Create an Entity
Entities are the core of TypeORM. They represent the tables in your database. Let's create a simple User entity.

Create a new directory called entities inside the src directory, and then create a file named user.entity.ts inside the entities directory:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Create a User Module and Service
To keep our code modular, we will create a user module and a corresponding service to handle our user-related logic.

Generate a new module and service:

nest generate module users
nest generate service users
Enter fullscreen mode Exit fullscreen mode

Now, update 'src/users/users.module.ts' to include TypeORM for our User entity:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersService } from './users.service';
import { User } from '../entities/user.entity';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}
Enter fullscreen mode Exit fullscreen mode

Step 6: Implement the Users Service
Open src/users/users.service.ts and implement basic CRUD operations:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: number): Promise<User> {
    return this.usersRepository.findOneBy({ id });
  }

  create(user: User): Promise<User> {
    return this.usersRepository.save(user);
  }

  async remove(id: number): Promise<void> {
    await this.usersRepository.delete(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Create a Users Controller
Generate a controller for users:

nest generate controller users
Enter fullscreen mode Exit fullscreen mode

Open src/users/users.controller.ts and set up the endpoints:

import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from '../entities/user.entity';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  findAll(): Promise<User[]> {
    return this.usersService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string): Promise<User> {
    return this.usersService.findOne(+id);
  }

  @Post()
  create(@Body() user: User): Promise<User> {
    return this.usersService.create(user);
  }

  @Delete(':id')
  remove(@Param('id') id: string): Promise<void> {
    return this.usersService.remove(+id);
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Integrate Users Module
Finally, integrate the UsersModule into our AppModule. Open src/app.module.ts and update it:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'database.sqlite',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
    UsersModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})

export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Running the Application
Now that everything is set up, you can run your application:

npm run start
Enter fullscreen mode Exit fullscreen mode

Your NestJS server should be running, and you can start interacting with your API. Try making some requests to the /users endpoint using Postman or any other API client to see your CRUD operations in action.

Conclusion
Congratulations! 🎉 You've just set up a basic NestJS application with TypeORM and implemented CRUD operations for a User entity. From here, you can expand your application by adding more entities, services, and controllers as needed.

NestJS and TypeORM provide a powerful combination for building scalable and maintainable applications. Keep exploring the NestJS and TypeORM documentation to unlock their full potential.

Happy coding! 🚀

Top comments (0)