들어가기
user의 profile을 edit 혹은 update하는 방법
중요한 것은 password를 edit할 경우, 반드시hash화 시켜야 하는데,
그 방법을 확실히 알아보자.
import { InputType, ObjectType, PartialType, PickType } from '@nestjs/graphql';
import { MutationOutput } from 'src/common/dtos/output.dto';
import { User } from '../entities/user.entity';
@ObjectType()
export class EditProfileOutput extends MutationOutput {}
///return은 ok, error이기 때문에 MutationsOutput만 extends 한다.
@InputType()
export class EditProfileInput extends PartialType(
PickType(User, ['email', 'password']),
) {}
///PickType으로 User entity의 email과 password를 Pick한 다음,
///PartialType으로 감싸서, 둘 중 하나, 혹은, 둘다 edit할 수 있게 해줌.
@UseGuards(AuthGuard) ///login된 user만 this fn을 사용할 수 있게 함.
@Mutation(() => EditProfileOutput)
async editProfile(
@AuthUser() authUser: User,
@Args('input') editProfileInput: EditProfileInput,
): Promise<EditProfileOutput> {
///@AuthUser을 넣어서, logggedInUser의 정보를 받을 수 있게 함.
try {
await this.usersService.editProfile(authUser.id, editProfileInput);
///authUser의 id와 editProfileInput의 dto를 입력한다.
return {
ok: true,
};
///성공적으로 edit했으면, true를 리턴한다.
} catch (error) {
return {
ok: false,
error,
};
}
}
@BeforeInsert()
@BeforeUpdate() ///@BeforeUpdate를 넣어서 edit시, password를 hash화 한다.
async hashPassword(): Promise<void> {
try {
this.password = await bcrypt.hash(this.password, 10);
} catch (e) {
console.log(e);
throw new InternalServerErrorException();
}
}
async editProfile(
userId: number,
{ email, password }: EditProfileInput, ///EditProfileInput dto에서
///email, password만 뽑아냄.
): Promise<User> {
///return은 User를 return해준다.
const user = await this.users.findOneBy({ id: userId });
///userId로 edit할려는 user를 찾는다.
if (email) {
user.email = email;
}
if (password) {
user.password = password;
}
///email, password가 들어오는 종류에 따라 user의 email, password를 바꿔준다.
return this.users.save(user);
///바뀐 user의 profile을 save해준다. update를 사용하지 않는 이유는
///update를 사용하면, entity를 거치지 않아,
///hashPassword, @BeforeUpdate()가 적용되지않는다
///그래서 update대신, save를 사용한다.
}
update혹은 editProfile하기 위해서는 update가 아닌 save를 사용하는데
이유는 entity에서 @BeforeUpdate를 작용시켜주기 위해서다.
update는 Entity를 거치지 않아 @BeforeUpdate가 먹히지 않음.
PartialType은 PickType에서 초이스한거중에 암거나 골라서, 혹은 다 골라서,
arg로 쓸 수 있다는 선택적 의미임.
@AuthUser Deco를 통해 logggdeInUser의 정보를 바로 받아볼수 있다.