NestJs Tutorial
준비 사항 (클릭 시 링크 이동)
insomnia
설치Postgresql
설치Postico
설치$ npm i -g @nestjs/cli
명령어
nest new [project_name]
: generate new nest project
nest g co contacts
|
Modules
모듈은 Nest 에서 가장 기본이 되는 구성요소, 하나의 어플리케이션은 여러 모듈의 조합으로 이뤄진다.
nest g mo contacts
|
Controllers
HTTP Method 요청 혹은 특정 요청에 따라 알맞은 응답 (routing)
nest g s contacts
|
Service
컨트롤러에서 받은 요청을 실제로 실행하는 구현부
Module
Controller
@Controller('movies')
: /movies 가 엔트리 포인트가 된다.
Service
NestJs DB connection
$ yarn add @nestjs/typeorm typeorm pg
// ormconfig.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "root",
"database": "test",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": true
}
// app.module
@Module({
controllers: [AppController],
providers: [AppService],
imports: [TypeOrmModule.forRoot(), ContactsModule],
})
run server 후 db connection 확인
Entity
: 엔티티의 필드와 타입 지정 -> service 레이어에서 DB와 트랜잭션 발생할 때 사용된다.@Module({
imports: [TypeOrmModule.forFeature([Entity이름])],
controllers: [ContactsController],
providers: [ContactsService],
})
export class ContactsModule {}
앱 서비스에서 생성자에 DB repository 주입: @InjectRepository
constructor(
@InjectRepository(Contact)
private contactRepository: Repository<Contact>,
) {}