티스토리 뷰
@Exclude()
@Entity()
export class User extends BaseEntity {
@ApiProperty()
@Expose()
@PrimaryGeneratedColumn('uuid', { name: 'user_id' })
id: string;
@ApiProperty({ default: '01024094270' })
@Expose()
@IsNotEmpty({ message: '휴대폰번호를 입력해주세요.' })
@IsPhone({ message: '휴대폰번호가 잘못 입력되었습니다.' })
@Column({ unique: true })
phone: string;
유저 모델이 위와 같이 정의되어있는 상황에 휴대폰 번호 자체의 문법적 오류(하나가 빠졌다던가, 이상한 번호를 입력했다던가)는 잘 걸러지는 상태이지만, 휴대폰번호가 이미 데이터베이스에 들어있는지 검증하는 로직은 빠져있었다.
그래서 아래와 같이 Custom Validator를 만들었다.
@ValidatorConstraint({ name: 'PhoneValidator' })
@Injectable()
export class PhoneValidator implements ValidatorConstraintInterface {
message = '휴대폰 번호가 잘못 입력되었습니다.';
constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {}
async validate(phone: string, { object }: ValidationArguments) {
try {
if (phone && !object['code']) {
this.message = '휴대폰 인증번호를 입력해주세요.';
return false;
}
if (phone && !(await this.authService.isPhoneAuthenticated(phone, object['code']))) {
this.message = '휴대폰번호를 인증해주세요.';
return false;
}
if (await this.usersService.findByPhone(phone)) {
this.message = '이미 사용중인 휴대폰번호입니다.';
return false;
}
} catch (e) {
return false;
}
return true;
}
defaultMessage(args: ValidationArguments) {
return this.message;
}
}
@Exclude()
@Entity()
export class User extends BaseEntity {
@ApiProperty()
@Expose()
@PrimaryGeneratedColumn('uuid', { name: 'user_id' })
id: string;
@ApiProperty({ default: '01024094270' })
@Expose()
@Validate(PhoneValidator) // Custom Validator 추가
@IsNotEmpty({ message: '휴대폰번호를 입력해주세요.' })
@IsPhone({ message: '휴대폰번호가 잘못 입력되었습니다.' })
@Column({ unique: true })
phone: string;
그리고나서 방금 만든 Custom Validator를 엔티티에 추가하고 나서 PickType을 활용하여 아래와 같이 Dto를 만들었다.
class UserDto extends IntersectionType(PickType(User, ['phone', 'thumbnail']) {};
전혀 아무런 문제가 없어야 정상이지만..
$ cross-env NODE_ENV=local node ./node_modules/typeorm/cli.js schema:drop
Error during schema drop:
TypeError: Cannot read property 'prototype' of undefined
at Object.PickType (/Users/simsimjae/Desktop/chium-back/node_modules/@nestjs/swagger/dist/type-helpers/pick-type.helper.js:13:39)
at Object.<anonymous> (/Users/simsimjae/Desktop/chium-back/dist/src/modules/auth/dto/auth.dto.js:24:60)
이런 이상한 오류를 내뱉었다.
나는 로컬에서 개발할때 스키마를 drop, sync, seeding을 순차적으로 진행하게끔 설정했는데 맨 처음에 스키마를 drop할때 문제가 발생했다.
원인을 찾아보고 난 결론은 Entity에 Validator가 섞여있게 되면 알 수 없는 오류가 발생할 가능성이 높아진다는것이다.
typeorm이 무언가 Entity를 조작하는 과정에서 Custom Validator 때문에 망가진것같으나 정확한 원인은 찾을 수 없었다.
그래서 아래와 같이 Validator와 Entity를 분리하는 방식으로 해결하였다.
class UserDto extends IntersectionType(PickType(User, ['phone', 'thumbnail']) {
@Validate(PhoneValidator)
phone: string;
};
'Nest.js' 카테고리의 다른 글
시/도 + 시/군/구 CSV파일 (0) | 2021.12.01 |
---|---|
전국에 있는 모든 시/군/구의 동/읍/면/리 데이터 (0) | 2021.11.23 |
댓글
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- storybook
- computed
- reactdom
- Polyfill
- design system
- es6
- hydrate
- useRef
- Next.js
- return type
- await
- props
- mobx
- reducer
- async
- state
- atomic design
- type alias
- react
- useEffect
- server side rendering
- rendering scope
- react hooks
- Action
- Babel
- webpack
- reflow
- javascript
- promise
- typescript
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함