Nest.js와 Express 비교

윤동환·2023년 1월 3일
0

Server

목록 보기
1/1

Nest.Js 란?

Nest (NestJS)는 효율적이고 확장 가능한 Node.js서버측 애플리케이션을 구축하기 위한 프레임워크입니다.
(express를 기본으로 채택하고 그 위에 여러 기능을 미리 구현해놓은 것이 nestjs)

특징

  • TypeScript, OOP, FP, FRP(기능 반응성 프로그래밍) 요소를 결합하여 효율성을 증가시킨다.
  • TypeScript를 적극 도입하여 발생 가능한 오류를 사전에 방지할 수 있다. (안정적)
  • 모듈로 감싸는 형태로 개발하여 모듈별 테스트 코드를 쉽게 작성할 수 있다.(안정적)
  • 모듈을 사용하여 확장이 용이하도록 설계되어있다.
  • TypeScript를 사용하여 DI(의존성 주입), IoC(제어의 역전), 모듈을 통한 구조화 등의 기술을 통해 생산성이 높다.
  • spring과 사용경험이 유사하고 spring보다 간단하다.

Express 란?

웹 및 모바일 애플리케이션을 위한 일련의 강력한 기능을 제공하는 간결하고 유연한 Node.js 웹 애플리케이션 프레임워크입니다.

특징

  • TypeScript를 사용할 수 있지만 ,tsconfig.json, lint.json등 세팅과정이 복잡하다.
  • 개발시 구조의 자유도가 높아 웹서버를 빠르게 구현할 수 있다.

사용시 차이

라우팅

express의 app.use로 등록해서 사용하는 것과 달리,
NestJs는 모듈별로 나누어서 라우팅을 하게 된다.

express

app.use('/user', require('./userRouter'))
app.use('/board', require('./boardRouter'))

Nest.Js

// NestJS
import { Module } from "@nestjs/common";
import { UsersController } from "./users.controller";
import { UsersService } from "./users.service";
//...

@Module({
  imports: [
    TypeOrmModule.forFeature([UsersRepository], DB_CONNECTION),
    S3ImageModule,
  ],
  providers: [UsersService, HttpService, ImageFileService],
  controllers: [UsersController],
})
export class UsersModule {}

컨트롤러

nestjs는 @Controller()의 경로와 더불어 class의 메소드의 데코레이터를 사용하여 추가적으로 원하는 작업 및 라우팅을 할 수 있다.

express

// Express
router.route('/')
	.get((req,res) => {
    //컨트롤러 로직
})

Nest.Js

// NestJS
import { Controller, Get, Post, Delete, Patch } from "@nestjs/common";
//...

@Controller("users")
export class UsersController {
  @Get()
  getAll() {
    return "users";
  }
  @Get("/:id")
  getOne(@Param("id") users: string) {
    return `one user id: ${users}`;
  }
  @Post()
  create() {
    return "This will create a user";
  }
  @Delete("/:id")
  remove(@Param("id") userId: string) {
    return `this will delete a user with the id : ${userId}`;
  }
  @Patch("/:id")
  path(@Param("id") userId: string, @Body() updateData) {
    return `this will patch a user with the id : ${userId}`;
  }
}

서비스

NestJs는 TypeORM을 사용하여 entity class를 지정하고, InjectRepository를 사용하여 변수로 선언한다. TypeORM에서 제공해주는 기능인 repository를 통해 CRUD를 실행 할 수 있다.

express

router.route('/')
	.get((req,res) => {
	// 서비스 로직
})

Nest.Js

import { Injectable } from '@nestjs/common';
import { DB_CONNECTION } from '../../configs/database/constants';
import { UserInput } from '../../common/dtos/userInput.dto';
import { CoreOutput } from '../../common/dtos/output.dto';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(UsersRepository, DB_CONNECTION)
    private readonly usersRepository: UsersRepository,
  ) {}

  /**
   * user 가입 생성
   * @param userInput
   * @returns
   */
  async create(
   userInput: UserInput,
  ): Promise<CoreOutput> {
    try {
    	await this.usersRepository.saveUser(
          userInput
        );
        
      return { ok: true, message: 'user create success' };
    } catch (error) {
      return { ok: false, message: 'error:' + error };
    }
  }```

profile
모르면 공부하고 알게되면 공유하는 개발자

0개의 댓글