TypeORM / Postgress 를 사용하여 데이터 베이스 연결하기
typeorm과 pg를 설치한다.
yarn add @nestjs/typeorm typeorm pg
TypeOrmModule 을 이용하여 서버시작시 데이터 베이스를 연결한다.
프로젝트 루트에 ormconfig.json파일을 생성하여 DB설정값을 입력한다.
entities에는 엔티티를 정의하는 파일의 정규식을 작성하면, TypeORM에서 정의된 엔티티를 읽어서 데이터베이스와 매핑한다.
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "jammanbo",
"password": "",
"database": "contacts",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": true
}
App moudle에 DB 연결코드를 추가한다.
@Module({
controllers: [AppController],
providers: [AppService],
imports: [TypeOrmModule.forRoot(), ContactsModule],
})
export class AppModule {}
데이터베이스가 성공적으로 연결되었다면 오류없이 서버가 실행된다.
contacts/entities/contact.entity.ts파일을 생성하고 Entity를 구현한다.
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Contact {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
detail: string;
}
Contact 모듈에서 Contact Entity를 Import 한다.
@Module({
imports: [TypeOrmModule.forFeature([Contact])],
controllers: [ContactsController],
providers: [ContactsService],
})
export class ContactsModule {}
이제 Entity와 데이터 베이스가 매핑이되어서 Entity를 생성, 수정, 삭제 할 수있다.
해당내용을 contacts 서비스에 구현해보자
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Contact } from './entities/contact.entity';
@Injectable()
export class ContactsService {
constructor(
@InjectRepository(Contact)
private contactRepository: Repository<Contact>,
) {}
// 전체 연락처 리스트를 가지고 온다.
findAll(): Promise<Contact[]> {
return this.contactRepository.find();
}
// 연락처를 가지고온다.(id)
findOne(id: number): Promise<Contact> {
return this.contactRepository.findOne(id);
}
// 연락처를 삭제한다.
async remove(id: number): Promise<void> {
await this.contactRepository.delete(id);
}
// 연락처를 추가한다.
create(name: string, age: number, detail: string) {
const contact = {
name,
detail,
age,
};
return this.contactRepository.save(contact);
}
// 연락처를 수정한다.
async update(id: number, name: string, age: number, detail: string) {
const contact = await this.contactRepository.findOne(id);
contact.name = name;
contact.age = age;
contact.detail = detail;
return this.contactRepository.save(contact);
}
}
또한 해당내용을 Controller에 추가한다.
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { ContactsService } from './contacts.service';
import { Contact } from './entities/contact.entity';
@Controller('contacts')
export class ContactsController {
constructor(private contactsService: ContactsService) {}
@Get()
async findAll(): Promise<Contact[]> {
return this.contactsService.findAll();
}
@Post()
async create(
@Body()
{ name, age, detail }: { name: string; age: number; detail: string },
): Promise<Contact> {
return this.contactsService.create(name, age, detail);
}
@Delete(':id')
async remove(@Param('id') id: number) {
console.log(id);
return this.contactsService.remove(id);
}
@Put(':id')
async update(
@Param('id') id: number,
@Body()
{ name, age, detail }: { name: string; age: number; detail: string },
) {
return this.contactsService.update(id, name, age, detail);
}
}