Nest (NestJS)는 효율적이고 확장 가능한 Node.js서버측 애플리케이션을 구축하기 위한 프레임워크입니다.
(express를 기본으로 채택하고 그 위에 여러 기능을 미리 구현해놓은 것이 nestjs)
웹 및 모바일 애플리케이션을 위한 일련의 강력한 기능을 제공하는 간결하고 유연한 Node.js 웹 애플리케이션 프레임워크입니다.
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 };
}
}```