해당 컨트롤러에 요청이 오기 전 Middleware에서 토큰을 통해 사용자를 인증하는 과정을 거침
해당 정보를 바탕으로 userId를 추출할 수 있는데 이를 Service에 넘겨 줌
정보 수정 시에는 username / bio / profile 개만 업데이트 가능 ( 현재 구현 시에는 )
Service
// 사용자 프로필 수정 함수
interface UpdateUserProfileProps {
userId: number;
username: string;
password: string;
bio: string;
profile?: string; // 만약 profile이 있다면 기존 profile을 삭제하고 새로운 profile을 저장
}
export const updateUserProfile = async (updateProps: UpdateUserProfileProps): Promise<void> => {
try {
const findUser = await userRepository.findOne({
where: { id: updateProps.userId }
});
if (!findUser) {
throw new Error('User not found');
}
if (!comparePassword({password: updateProps.password, hashedPassword: findUser.password})) {
throw new Error('Password is incorrect');
}
// update user profile data
findUser.username = updateProps.username;
findUser.bio = updateProps.bio;
// if profile exists, delete old profile and save new profile
if (updateProps.profile) {
if (findUser.profile) {
deleteUserProfile(findUser.profile);
}
findUser.profile = updateProps.profile;
}
// 업데이트 해준 후 저장
await userRepository.save(findUser);
return
} catch (error) {
handleError({error, message: 'Failed to update user profile'});
throw error;
}
}
userId를 통해 사용자 정보를 객체로 가져옴
수정 요청 시에 입력한 비밀번호와 현재 객체의 비밀번호가 동일한 지 확인
사용자 프로필이 기존에 있다면 해당 파일은 삭제해주고 프로필이 없다면 프로필 정보 업데이트