09-Relations
1. SQL 관계
- foreign key를 알고 있으면, 해당 키에 데이터를 굳이 가질 필요가 없다.
2. UserModel 생성
이제 다시 typeorm용 폴더가 아닌 기존 rest-server로 실습을 진행한다. 그 다음 user 모델을 nest cli 명령어로 생성한다.
shellscript
1nest g resource2? What name would you like to use for this resource? users3? What transport layer do you use? REST API4? Would you like to generate CRUD entry points? No
그리고 cli로 만들면, 자동으로 app 모듈에 방금 생성한 모듈을 추가해준다.
src/users/entities/users.entity.ts 파일은 만든다.
users.entity.ts
1import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'23@Entity()4export class UsersModel {5@PrimaryGeneratedColumn()6id: number78@Column()9nickname: string1011@Column()12email: string1314@Column()15password: string16}
app 모듈에 UsersModel을 추가한다.
app.module.ts
1@Module({2imports: [3PostsModule,4TypeOrmModule.forRoot({5// 생략6// entities폴더에 작성한 모듈 가져오기7entities: [PostsModel, UsersModel],8synchronize: true,9}),10UsersModule,11],12controllers: [AppController],13providers: [AppService],14})
3. Column 옵션 종류
@Column을 Cmd + 마우스 왼쪽 로 클릭하면, 명세서가 나온다.
users.entity.ts
1import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'23@Entity()4export class UsersModel {5@PrimaryGeneratedColumn()6id: number78/*** 닉네임 특성9* 1) 길이가 20을 넘지 않을 것10* 2) 유일무이한 값이 될 것11*/12@Column({13length: 20,14unique: true,15})16nickname: string1718/*** 이메일 특성19* 1) 유일무이한 값이 될 것20*/21@Column({22unique: true,23})24email: string2526@Column()27password: string28}
4. Enum Column 생성
users/const/roles.const.ts 파일을 만듭니다.
roles.const.ts
1export enum RolesEnum {2ADMIN = 'ADMIN',3USER = 'USER',4}
cf, enum 타입은 TS에서 제공하는 명명된 상수의 집합을 나타내는 데이터 타입
users.entity.ts
1@Entity()2export class UsersModel {3// 생략45@Column({6// role 특성의 타입을 RolesEnum의 모든 값들로 지정7enum: Object.values(RolesEnum),8default: RolesEnum.USER,9})10role: RolesEnum11}
5. User 관련 서비스 및 컨트롤러 작성
users.module.ts
1// 생략23@Module({4// 이 모듈 안에서 UsersModel을 어디서든 사용 가능5imports: [TypeOrmModule.forFeature([UsersModel])],6controllers: [UsersController],7providers: [UsersService],8})9export class UsersModule {}
유저 서비스를 만든다.
users.service.ts
1import { Injectable } from '@nestjs/common'2import { InjectRepository } from '@nestjs/typeorm'3import { UsersModel } from './entities/users.entity'4import { Repository } from 'typeorm'56@Injectable()7export class UsersService {8constructor(9@InjectRepository(UsersModel)10private readonly userRepository: Repository<UsersModel>,11) {}1213async createUser(nickname: string, email: string, password: string) {14const user = this.userRepository.create({15nickname,16email,17password,18})19const newUser = await this.userRepository.save(user)20return newUser21}2223async getAllUsers() {24return this.userRepository.find()25}26}
위에서 만든 서비스 기능을 사용할 컨트롤러를 만든다.
users.controller.ts
1import { Body, Controller, Get, Post } from '@nestjs/common'2import { UsersService } from './users.service'34@Controller('users')5export class UsersController {6constructor(private readonly usersService: UsersService) {}78@Get()9getUsers() {10return this.usersService.getAllUsers()11}1213@Post()14postUser(15@Body('nickname') nickname: string, //16@Body('email') email: string,17@Body('password') password: string,18) {19return this.usersService.createUser(nickname, email, password)20}21}
6. Author 관계 생성
포스트 엔티티에 다대일 관계를 넣어준다.
posts.entity.ts
1@Entity()2export class PostsModel {3@PrimaryGeneratedColumn()4id: number56/*** 작성자 1명이 여러 개의 포스트를 작성7* 1) UserModel과 연동한다 (Foreign Key를 사용해서)8* 2) null이 될 수 없다9*/10// one에 해당하는 클래스 타입을 넣어주면 된다11// 이 클래스 타입을 두 번쨰 함수의 파라미터로 받을 수 있다.12// 어떤 파라미터와 연동시킬지 선택13@ManyToOne(() => UsersModel, user => user.posts, {14nullable: false,15})16author: UsersModel1718// 생략19}
유저 엔티티에 일대다 관계를 넣어준다.
users.entity.ts
1@Entity()2export class UsersModel {3// 생략45@OneToMany(() => PostsModel, post => post.author)6posts: PostsModel[]7}
7. 에러 해결 및 DB 초기화
posts 서비스에 보면 author 부분에 에러가 날 겁니다. author가 string이였다가, UsersModel로 변경되어서 생긴겁니다.
posts.service.ts
1// posts.service.ts2/**3* 1) create : 저장할 객체를 생성4* 2) save : 객체를 저장 (create aㅔ서드에서 생성한 객체로)5*/6async createPost(authorId: number, title: string, content: string) {7const post = this.postsRepository.create({8author: {9id: authorId,10},11title,12content,13likeCount: 0,14commentCount: 0,15})1617const newPost = await this.postsRepository.save(post)1819return newPost20}2122/** save의 2가지 기능23* 1) 만약에 데이터가 존재하지 않는다면(id 기준) 새로 생성한다.24* 2) 만약에 데이터가 존재한다면(같은 id의 값이 존재한다면) 존재하던 값을 업데이트한다.25*/26async updatePost(postId: number, title: string, content: string) {27const post = await this.postsRepository.findOne({28where: { id: postId },29})3031if (!post) throw new NotFoundException()32if (title) post.title = title33if (content) post.content = content3435const newPost = await this.postsRepository.save(post)36return newPost37}
posts.controller.ts
1// posts.controller.ts 생략2/*** 3) POST /posts3* post를 생성한다4*/5@Post()6postPosts(7@Body('authorId') authorId: number, //8@Body('title') title: string,9@Body('content') content: string,10) {11return this.postsService.createPost(authorId, title, content)12}1314/*** 4) PATCH /posts/:id15* id에 해당하는 post를 부분 변경한다16*/17@Patch(':id')18putPost(19@Param('id') id: string, //20@Body('title') title?: string,21@Body('content') content?: string,22) {23return this.postsService.updatePost(+id, title, content)24}
넣은 데이터들 때문에 author가 null인 경우가 있을 수 있기에, DB 초기화해줍니다.
8. 관계를 이용해 데이터 생성
- posts와 users의 관계를 PostMan으로 데이터를 생성한다.
9. 관계 포함한 쿼리 작성
posts.service.ts
1// posts.service.ts 생략2async getAllPosts() {3return this.postsRepository.find({ relations: ['author'] })4}56async getPostById(id: number) {7const post = await this.postsRepository.findOne({8// PostsModel의 id가 입력받은 id와 같은지 필터링9where: {10id,11},12relations: ['author'],13})14if (!post) {15throw new NotFoundException()16}17return post18}