* 엔티티에서 @Unique 딸깍
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, Unique } from "typeorm";
@Entity()
@Unique(['username'])
export class User extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
}
* 원인 : 에러가 그냥 컨트롤러 레벨로 가서 500에러를 던져버림
해결 : 에러를 try catch로 잡아줘야함
리포지토리에서 save를 try-catch 안에 넣어주면됨.
@Injectable()
export class UserRepository extends Repository<User>{
constructor(dataSource: DataSource) {
super(User, dataSource.createEntityManager());
}
async createUser(authCredentialsDto : AuthCredentialsDto){
const {username, password} = authCredentialsDto;
const user = this.create({username,password}); //리포지토리.create => db저장용객체로 만들어줌
try {
await this.save(user);
} catch (error){
console.log(error);
}
}
}
에러코드 23505 == already key error 코드임 -> 메시지 찍어주면 되겠다.
async createUser(authCredentialsDto : AuthCredentialsDto){
const {username, password} = authCredentialsDto;
const user = this.create({username,password}); //리포지토리.create => db저장용객체로 만들어줌
try {
await this.save(user);
} catch (error){
if(error.code==='23505'){
throw new ConflictException('Existing username');
}
else{
throw new InternalServerErrorException();
}
}
}
}
'JS > Nest.js' 카테고리의 다른 글
[Nest JS] 로그인 구현 / bcrypt.compare salt issue (0) | 2024.08.18 |
---|---|
[Nest JS] 비밀번호 암호화 구현 (0) | 2024.08.18 |
[Nest JS] 유효성체크 with class-validator, 파이프 (0) | 2024.08.18 |
[Nest JS] 회원가입 구현 / TypeError: this.userRepository.createUser is not a function 해결 (0) | 2024.08.18 |
[Nest JS] 인증 구현 준비 (컨트롤러, 서비스, 리포지토리 생성) (0) | 2024.08.18 |