NestJS는 TypeScript로 작성되었으며, NodeJS 기반의 백엔드 프레임워크 입니다. Express를 기반으로 동작하며, 모듈화(Modular), 의존성 주입(Dependency Injection), 데코레이터 기반 프로그래밍을 지원합니다.
NestJS는 애플리케이션을 모듈 단위로 구성합니다.
모듈은 특정 기능을 캡슐화하며, 코드의 재사용성을 높이고 유지보수를 쉽게 만듭니다.
import { Module } from '@nestjs/common';
@Module({
imports: [],
controllers: [],
providers: [],
})
export class AppModule {}
컨트롤러는 클라이언트의 요청을 받아 처리하는 역할을 합니다.
import { Controller, Get } from '@nestjs/common';
@Controller('users') // '/users' 경로를 처리
export class UserController {
@Get()
findAll() {
return "모든 유저 조회";
}
}
서비스는 컨트롤러에서 호출되며, 실제 비즈니스 로직을 수행하는 역할을 합니다.
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserService {
getUsers() {
return ['User1', 'User2', 'User3'];
}
}
NestJS는 의존성 주입(DI)을 기본적으로 지원하여, 객체 간의 결합도를 낮추고 관리하기 쉽게 합니다.
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
findAll() {
return this.userService.getUsers();
}
}
NestJS는 레이어드 아키텍처(Layered Architecture) 또는 클린 아키텍처(Clean Architecture) 패턴을 따릅니다.
Controller → 요청(Request) 처리, 응답(Response) 반환
Service → 비즈니스 로직 수행
Repository (선택적) → 데이터베이스와의 연결을 담당 (TypeORM, Prisma 등 사용)
Module → 관련된 기능을 묶어 관리
데이터 흐름 예시
Client → Controller → Service → Repository (DB) → Service → Controller → Response
NestJS는 기능별로 모듈을 나누어 유지보수가 용이합니다.
예를 들어, UserModule
, AuthModule
, ProductModule
등으로 구성할 수 있습니다.
@Module({
imports: [UserModule, AuthModule, ProductModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
@Controller
, @Injectable
등) 싱글톤 패턴은 클래스의 인스턴스를 단 하나만 생성하도록 보장하는 디자인 패턴이기에
프로그램 전체에서 특정 객체를 하나만 유지하면서 공유할 수 있도록 해줍니다.
// singletonCar.ts
class Car {
private name = "";
private price = 0;
private company = "";
constructor(name: string, price: number, company: string) {
this.name = name;
this.price = price;
this.company = company;
}
info() {
console.log(
`이 차의 이름은 ${this.name}이고 가격은 ${this.price}고 제조사는 ${this.company} 입니다.`
);
}
}
// Car 객체를 생성하여 export (싱글톤처럼 동작)
export const Bugatti = new Car("부가티", 10000, "부가티오토모빌스");
Car
클래스는 자동차 정보를 저장하는 역할 Bugatti
객체는 new Car()
로 생성한 단 하나의 인스턴스 export const Bugatti
로 동일한 인스턴스를 여러 파일에서 공유 // user.ts
import { Bugatti } from "./singletonCar";
Bugatti.info(); // 이 차의 이름은 부가티이고 가격은 10000고 제조사는 부가티오토모빌스 입니다.
// app.js
import { Bugatti } from "./singletonCar.js";
Bugatti.info(); // 동일한 객체를 사용
singletonCar.ts
에서 Bugatti
객체를 이미 생성하고 export
import { Bugatti } from "./singletonCar"
하면 동일한 인스턴스를 공유 Bugatti
를 가져와도 새로운 객체를 만들지 않음