Hello,

kok nae-ga ha-myun an-dweneun MAGIC...🧚

웹 프로그래밍

[TypeORM] update시 @BeforeUpdate가 작동하질 않아 😩

✿도담도담 2022. 3. 19. 19:38

nestJS에서 typeORM과 함께 백엔드를 공부하고있는데

User 정보를 업데이트 하는 과정에서 비밀번호를 암호와 해야 했기에

@BeforeUpdate()를 사용해주었는데 작동을 안하잖아..?

 

💡기존 코드

// user.entitiy.ts
@BeforeInsert()
@BeforeUpdate()
async hashPassword(): Promise<void> {
    try {
        this.password = await bcrypt.hash(this.password, 10);
    } catch (error) {
        console.log(error);
        throw new InternalServerErrorException();
    }
}

/******************************************************************/

// user.service.ts
async editProfile(
	userId: number, { email, password }: EditProfileInput
): Promise<Users> {
	return this.users.update(userId, { ...editProfileInput });    
}

 

 

분명 나는 update() 함수를 호출했는데 왜 @BeforeUpdate가 호출되지않고

패스워드는 평서문으로 저장이 되고 있었다.

 

원인을 찾기위해 update 설명을 읽어보면,

"Does not check if entity exist in the database."

update의 경우에 우린 "query" 를 넘겨주고 있는것 뿐 entitiy는 체크하지 않는다!

따라서, 나는 update가 아닌 save를 사용해주기로 했다.

save() : If entity does not exist in the database then inserts, otherwise updates.

             데이터가 존재하지 않는다면 insert, 있다면 update

 

 

💡수정된 코드

 

async editProfile(userId: number, { email, password }: EditProfileInput): Promise<Users> {
    const user = await this.users.findOne(userId);
    if (email) {
        user.email = email;
    }
    if (password) {
        user.password = password;
    }

    return this.users.save(user);
}

 

 

남겨 놓으면 좋은 정보인것 같아 오랜만에 메모해놓는다 :>

노드 백엔드 공부중인데 진짜 갸어렵다 🤯