728x90
User의 Profile을 Update! (email & password)
// users.resolver.ts
...
@UseGuards(AuthGuard)
@Mutation((returns) => EditProfileOutput)
async editProfile(
@AuthUser() authUser: User,
@Args('input') editProfileInput: EditProfileInput,
): Promise<EditProfileOutput> {
try {
await this.userService.editProfie(authUser.id, editProfileInput);
return {
ok: true,
};
} catch (error) {
return { ok: false, error };
}
}
...
// users.service.ts
...
async editProfie(userId: number, { email, password }: EditProfileInput) {
const user = await this.users.findOne({ where: { id: userId } });
if (email) {
user.email = email;
}
if (password) {
user.password = password;
}
return this.users.save(user);
}
...
update시 언제 update를 할지, 언제 object를 찾을지 정말 중요하다.
이 경우에는 login되어 있지 않다면 누구도 editProfile을 호출할 수 없기 때문에
별도의 확인 없이 update 실행.
이 경우 entity를 update를 할 때 사용하는 BeforeUpdate()를 호출하지 않는다. password hashing을 위해
BeforeUpdate()를 실행할 필요가 있다. 그래서 update 대신에 save를 사용.
save()의 특징이 하나 있는데, entity를 save에 넘길 때 이미 존재하는 entity의 경우 update를 하고
없는 경우에 insert한다.
return this.users.update(userId, { ...editProfileInput });
➡ userId 존재 여부 상관 없이 update하는 빠른 함수.
728x90
'Node.js > NestJs' 카테고리의 다른 글
Unit Testing (0) | 2023.04.22 |
---|---|
Email Verification (0) | 2023.04.22 |
[User] Authentication #5 AuthUser Decorator (0) | 2023.04.08 |
[User] Authentication #4 Guard (0) | 2023.04.08 |
[User] Authentication #3 JWT Middleware (0) | 2023.04.08 |
댓글