HTTP 메소드 PUT / PATCH 의 차이점
🐳 PUT 메소드와 PATCH 메소드의 차이
PUT 메소드는 저장돼 있는 리소스 전체를 대체하고 PATCH는 일부 필드만을 대체한다.
PUT은 폴더에 파일을 옮기는 거라고 생각하면 편하다 ! - 김영한님이 HTTP 강좌에서 사용한 비유다
파일이 폴더 내에 없다면 파일이 새로 생기지만 이미 있는 경우 파일을 덮어버린다 !
PATCH는 파일을 열어 내용을 수정하는 것이라고 생각하면 편하다
import { BaseTimeEntity } from 'src/BaseTimeEntity';
import { Column, Entity } from 'typeorm';
@Entity()
export class User extends BaseTimeEntity {
@Column()
username: string;
@Column()
password: string;
@Column()
description: string;
@Column()
address: string;
}
const hoo: User = {
username: 'hoo',
password: 'my password',
description: 'Gwangjin Whales',
address: 'Gwangjin Gu',
};
위의 코드처럼 User Entity의 객체 hoo 가 있다고 가정해보자
내가 address column 을 수정하고 싶다면 어떻게 해야할까 ?
🐳 예시로 보는 PUT 과 PATCH의 차이
hoo User 객체의 address를 Seoul로 수정하고 싶다고 하자 그러면 어떤 정보를 보내야 할까? ( JSON 객체를 보낸다고 가정하자 ! )
PUT은 객체 전체를 대체하기 때문에 전체 내용을 보내줘야 한다
// address만 수정하고 싶지만 username, password, description, address 모두 보내야 한다
const updateUserDto = {
username: 'hoo',
password: 'my password',
description: 'Gwangjin Whales',
address: 'Seoul',
};
PATCH는 수정하고 싶은 내용의 객체만 보내주면 된다 !
// 수정하고 싶은 column의 내용만 보내주면 된다 !
const updateUserDto = {
address: 'Seoul'
};
🐳 Utility Type을 활용한 PartialType 구현
export class CreateUserDto {
@Column()
username: string;
@Column()
password: string;
@Column()
description: string;
@Column()
address: string;
}
프론트에서 주는 객체를 검증하기 위해 CreateUserDto를 사용한다고 가정하자
이 때 PATCH 메소드는 4개의 필드 중 일부 속성만을 가진다.
그러면 4개의 필드 중 n개를 고르는 UpdateUserDto는 어떻게 구현하는게 좋을까?
생각보다 복잡한 과정일 것 같고 여러 각 필드가 있을 경우와 없는 경우를 if 문을 이용해 구현해야 할 것 같다.
하지만 NestJS는 이런 번거로움을 도와주기 위해 PartialType 기능을 지원한다.
코드 한 줄로 끝난다 ! 아래의 코드를 보자
( 먼저 PartialType을 구현하기 위해서 @nestjs/swagger module을 설치해주자 )
import { PartialType } from '@nestjs/swagger';
import { CreateUserDto } from './createUserDto';
export class UpdateUserDto extends PartialType(CreateUserDto) {}
이렇게 하면 CreateUserDto의 일부 필드만을 가지는 UpdateUserDto 구현 끝 ! ( 일부만을 수정해야 하므로 PATCH 메소드를 사용해야 한다. )
🐳 결론
예제와 함께 PUT 과 PATCH의 차이를 알아보았다.
각각의 쓰임새가 다르므로 차이점을 잘 알고 올바르게 사용하도록 하자 !