티스토리 뷰
원하는 기능을 만들기 위해 먼저 Car에 대한 레코드를 다음과 같이 만들었다.
![](https://blog.kakaocdn.net/dn/wTjGC/btraLtlbdk2/KVYKxLAE09oaItkGjYISh1/img.png)
유저가 자동차를 구매하여 해당 유저의 Car정보를 업데이트 해야하는 상황이라고 가정해 보자.
/user/:id
에 patch 요청을 보내면 해당 body를 업데이트 하는 식으로 car정보를 업데이트 해보겠다.
먼저 update-user.dto.ts
파일을 작성했다.
이때, update-user.dto.ts
파일은 create-user.dto.ts
파일과 매우 유사한 구조를 갖는다.
다만 컬럼을 옵션으로 가질 뿐이다. 이때는 같은 코드를 다시 작성하지 않고 mapped-types
의 PartialType
을 이용하면 된다.
yarn add @nestjs/mapped-types
를 설치하자.
그 다음 아래와 같이 코드를 작성하자.
import { PartialType } from '@nestjs/mapped-types';
import { createUserDto } from './create-user.dto';
export class updateUserDto extends PartialType(createUserDto) {}
다음 user.controller.ts
와 user.service.ts
를 수정했다.
//user.controller.ts
@Patch(':id')
updateCarById(@Param('id') id: number, @Body() userData: updateUserDto) {
const { car: carId } = userData;
return this.userService.updateCarById(id, carId);
}
//user.service.ts
async updateCarById(id: number, carId: Car) {
try {
const car = await this.carRepository.findOne(carId);
console.log(car);
if (!car)
throw new NotFoundException(`car not found with the id ${carId}`);
const user = await this.userRepository.findOne(id);
user.car = car;
console.log(user);
this.userRepository.save(user);
} catch (err) {
console.error(err)
}
}
먼저 car의 id를 가지고 car정보를 불러오고, user의 id를 통해 user정보를 가져온다.
그리고 user의 car정보에 데이터를 업데이트하고 save해주면 된다.
이제 patch요청을 한번 보내보자.
body에 car의 id를 담아서 patch 요청을 보내면 된다.
예를들어 user/2
의 주소로 {"car" : 1}
이라는 바디를 담아 패치요청을 보냈다.
요청이 정상적으로 들어간 것 같은데 /user
에 들어가보면 해당 정보가 나오지 않는다.
따라서, user.entity.ts
파일에 이 코드를 추가해주었다. (참고)
@Column({ nullable: true })
carId: number;
이제 다시 요청을 해보면
![](https://blog.kakaocdn.net/dn/Pe9UO/btraMqognzo/t8qx3kMIH43QUk271CKfzK/img.png)
이런식으로 carId가 담겨오는 것을 확인할 수 있다.
이제 마지막으로, user의 carId를 이용하여 이 유저의 car정보를 받아오자.
//user.controller.ts
@Get('car/:id')
getCarInfo(@Param('id') id: number): Promise<Car> {
return this.userService.getCarInfo(id);
}
//user.controller.ts
async getCarInfo(id: number): Promise<Car> {
const user = await this.userRepository.findOne(id);
if (!user || !user.carId) throw new NotFoundException(`not found error`);
const carInfo = await this.carRepository.findOne(user.carId);
return carInfo;
}
간단하게 이렇게 작성해보았다.
또 다른 방법으로는
async getCarInfo(id: number): Promise<Car> {
const user = await this.userRepository.findOne(id, { relations: ['car'] })
return user.car
}
이렇게 작성하는 방법이 있다. 물론 예외처리는 따로 해줘야 한다.
이 외에도 조인을 하는 방법은 다양하다. 공식문서에 자세히 나와있다.
/user/car/2
로 접속하면 2번유저의 car의 정보를 받아올 수 있다.
http localhost:3000/user/car/2
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 114
Content-Type: application/json; charset=utf-8
Date: Thu, 29 Jul 2021 16:36:04 GMT
ETag: W/"72-cpoOW5maPuyn/pAp4QLGnL6lJe4"
Keep-Alive: timeout=5
X-Powered-By: Express
{
"createdAt": "2021-07-29T16:12:15.540Z",
"id": 1,
"model": "bmw",
"price": 50000,
"updatedAt": "2021-07-29T16:12:15.540Z"
}
이렇게 말이다.
다음은 마지막으로 OneToMany, ManyToOne, ManyToMany 관계를 작성하고 테스트해보자.
'Node.js' 카테고리의 다른 글
Nest.js + typeORM 으로 REST API 서버 만들기 (7) (2) | 2021.07.30 |
---|---|
Nest.js + typeORM 으로 REST API 서버 만들기 (5) (0) | 2021.07.29 |
Nest.js + typeORM 으로 REST API 서버 만들기 (4) (0) | 2021.07.29 |
Nest.js + typeORM 으로 REST API 서버 만들기 (3) (0) | 2021.07.29 |
Nest.js + typeORM 으로 REST API 서버 만들기 (2) (0) | 2021.07.29 |
- Total
- Today
- Yesterday
- BFS
- 그래프
- 재귀
- 자바스크립트
- java
- nest.js
- 알고리즘
- 투포인터
- 백트래킹
- 스레드
- 백준
- 시뮬레이션
- 세그먼트 트리
- 컴퓨터 구조
- typeORM
- ReactNative
- node.js
- 구현
- Computer Architecture
- 중앙대학교
- 자바
- 예외처리
- 그리디
- boj
- dfs
- 동적계획법
- 컴퓨터 통신
- nodeJS
- nestjs
- 벨만포드
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |