Commit c016fafd authored by Yoon, Daeki's avatar Yoon, Daeki 😅
Browse files

서버 프로필 업데이트 로직 수정 변경

parent add2d2b3
...@@ -30,34 +30,36 @@ export const getProfile = asyncWrap(async (reqExp, res) => { ...@@ -30,34 +30,36 @@ export const getProfile = asyncWrap(async (reqExp, res) => {
res.json(profile); res.json(profile);
}); });
export const postPicture = asyncWrap(async (reqExp, res) => { export const updateProfile = asyncWrap(async (reqExp, res) => {
const req = reqExp as TypedRequest; const req = reqExp as TypedRequest;
const { userId } = req.auth; const { userId } = req.auth;
const field = req.body; const { name } = req.body;
const file = req.files; const { avatar }: { avatar: formidable.File } = req.files;
if (!Array.isArray(file.picture)) { const user = await userDb.updateProfile(userId, name, avatar);
//파일 좁히기 중
if (!Array.isArray(field.nickname)) { // if (!Array.isArray(file.avatar)) {
const nickname = field.nickname; // //파일 좁히기 중
if (!(file.picture === undefined)) { // if (!Array.isArray(field.nickname)) {
const originalfilename = file.picture.originalFilename; // const nickname = field.nickname;
const newfilename = file.picture.newFilename; // if (!(file.avatar === undefined)) {
const picturepath = file.picture.filepath; // const originalfilename = file.avatar.originalFilename;
userDb.postPicture( // const newfilename = file.avatar.newFilename;
userId, // const picturepath = file.avatar.filepath;
nickname, // userDb.updateProfile(
originalfilename, // userId,
newfilename, // nickname,
picturepath // originalfilename,
); // newfilename,
} else { // picturepath
userDb.postPicture(userId, nickname); // );
} // } else {
} // userDb.updateProfile(userId, nickname);
} // }
// }
// }
res.json(); res.json(user);
}); });
export const deleteUser = asyncWrap(async (reqExp, res) => { export const deleteUser = asyncWrap(async (reqExp, res) => {
......
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import { ObjectId } from "mongoose"; import { HydratedDocument, ObjectId } from "mongoose";
import { IUser, Role, Post, User, FileInfo, IRole } from "../models"; import { IUser, Role, Post, User, FileInfo, IRole, IFileInfo } from "../models";
import fs from "fs/promises"; import fs from "fs/promises";
import formidable from "formidable";
export const createUser = async (user: IUser) => { export const createUser = async (user: IUser) => {
// 비밀번호 암호화 // 비밀번호 암호화
...@@ -16,6 +17,7 @@ export const createUser = async (user: IUser) => { ...@@ -16,6 +17,7 @@ export const createUser = async (user: IUser) => {
} }
const newUser = new User({ const newUser = new User({
email: user.email, email: user.email,
name: user.name,
password: hash, password: hash,
role: userRole, role: userRole,
isNew: true, isNew: true,
...@@ -46,7 +48,7 @@ export const findUserByPostId = async (postId: string) => { ...@@ -46,7 +48,7 @@ export const findUserByPostId = async (postId: string) => {
}; };
export const getProfile = async (userId: string) => { export const getProfile = async (userId: string) => {
const profile = await User.findById(userId).populate("fileInfo"); const profile = await User.findById(userId).populate("avatar");
return profile; //이름 수정 return profile; //이름 수정
}; };
...@@ -73,48 +75,87 @@ export const isValidUserId = async (userId: string) => { ...@@ -73,48 +75,87 @@ export const isValidUserId = async (userId: string) => {
} }
}; };
export const postPicture = async ( export const updateProfile = async (
userId: ObjectId, userId: ObjectId,
nickname: string, name: string,
originalfilename?: string | null, avatar: formidable.File
newfilename?: string,
picturepath?: string
) => { ) => {
const profile = await User.findById(userId); const user = await User.findById(userId).populate<{ avatar: IFileInfo }>(
"avatar"
if (!(profile?.fileInfo === undefined)) { );
if (originalfilename === null) { console.log("user in update profile", user, avatar);
await FileInfo.findByIdAndUpdate(profile.fileInfo._id, { if (!user) {
nickname: nickname, throw new Error("사용자가 존재하지 않습니다");
}); }
} else if (nickname === "") { if (avatar) {
const ref = FileInfo.findById(profile.fileInfo._id); if (!user.avatar) {
console.log(ref); // 사용자의 아바타가 존재하지 않으면 생성
const file = await FileInfo.create({
await FileInfo.findByIdAndUpdate(profile.fileInfo._id, { originalfilename: avatar.originalFilename,
originalfilename: originalfilename, newfilename: avatar.newFilename,
newfilename: newfilename, picturepath: avatar.filepath,
picturepath: picturepath,
}); });
user.avatar = file;
} else { } else {
const ref = await FileInfo.findByIdAndUpdate(profile.fileInfo._id, { // 아바타에 같은 원래파일이름이 존재하는지 확인
originalfilename: originalfilename, // 같으면 파일 수정하지 않고 통과
newfilename: newfilename, if (
picturepath: picturepath, avatar.originalFilename &&
nickname: nickname, user.avatar.originalfilename !== avatar.originalFilename
}); ) {
// 같지 않으면 기존의 파일을 디스크에서 삭제한 후
try {
await fs.unlink(user.avatar.picturepath);
} catch (error) {
console.log("error", error);
}
const userAvatar = user.avatar as HydratedDocument<IFileInfo>;
// 기존 아바타 fileinfo의 파일이름과 경로 변경 설정
userAvatar.originalfilename = avatar.originalFilename;
userAvatar.newfilename = avatar.newFilename;
userAvatar.picturepath = avatar.filepath;
await userAvatar.save();
}
} }
} }
user.name = name;
await user.save();
console.log("user updated", user);
return user;
// if (!(profile?.avatar === undefined)) {
// if (originalfilename === null) {
// await FileInfo.findByIdAndUpdate(profile.avatar._id, {
// nickname: nickname,
// });
// } else if (nickname === "") {
// const ref = FileInfo.findById(profile.avatar._id);
// console.log(ref);
// await FileInfo.findByIdAndUpdate(profile.avatar._id, {
// originalfilename: originalfilename,
// newfilename: newfilename,
// picturepath: picturepath,
// });
// } else {
// const ref = await FileInfo.findByIdAndUpdate(profile.avatar._id, {
// originalfilename: originalfilename,
// newfilename: newfilename,
// picturepath: picturepath,
// nickname: nickname,
// });
// }
// }
}; };
export const deleteUser = async (userId: string) => { export const deleteUser = async (userId: string) => {
const user = await User.findById(userId); const user = await User.findById(userId);
if (!(user?.fileInfo === undefined)) { if (!(user?.avatar === undefined)) {
const ref = await FileInfo.findById(user.fileInfo._id); const ref = await FileInfo.findById(user.avatar._id);
if (!(ref?.newfilename === undefined)) { if (!(ref?.newfilename === undefined)) {
await fs.unlink("../travel/uploads/" + ref?.newfilename); await fs.unlink("../travel/uploads/" + ref?.newfilename);
} }
await FileInfo.deleteOne({ _id: user.fileInfo._id }); await FileInfo.deleteOne({ _id: user.avatar._id });
const finish = await User.deleteOne({ _id: userId }); const finish = await User.deleteOne({ _id: userId });
return finish; return finish;
} }
......
...@@ -5,7 +5,7 @@ export interface IUser { ...@@ -5,7 +5,7 @@ export interface IUser {
name?: string; name?: string;
password: string; password: string;
role?: Types.ObjectId; role?: Types.ObjectId;
fileInfo?: Types.ObjectId; avatar?: Types.ObjectId;
} }
const validateEmail = (email: string) => { const validateEmail = (email: string) => {
...@@ -22,7 +22,7 @@ const schema = new Schema<IUser>( ...@@ -22,7 +22,7 @@ const schema = new Schema<IUser>(
validate: [validateEmail, "이메일을 입력해주세요"], validate: [validateEmail, "이메일을 입력해주세요"],
}, },
name: { type: String }, name: { type: String },
fileInfo: { type: Schema.Types.ObjectId, ref: "FileInfo" }, avatar: { type: Schema.Types.ObjectId, ref: "FileInfo" },
password: { type: String, required: true, select: false }, password: { type: String, required: true, select: false },
role: { type: Schema.Types.ObjectId, ref: "Role" }, role: { type: Schema.Types.ObjectId, ref: "Role" },
}, },
......
...@@ -6,7 +6,7 @@ const router = express.Router(); ...@@ -6,7 +6,7 @@ const router = express.Router();
router router
.route("/") .route("/")
.get(authCtrl.requireLogin, userCtrl.getProfile) .get(authCtrl.requireLogin, userCtrl.getProfile)
.post(authCtrl.requireLogin, fileInfoCtrl.uploadFile, userCtrl.postPicture); //중간에 req쪽에 fields와 files 넣는 미들웨어 추가 .post(authCtrl.requireLogin, fileInfoCtrl.uploadFile, userCtrl.updateProfile); //중간에 req쪽에 fields와 files 넣는 미들웨어 추가
router.route("/delete").delete(authCtrl.requireLogin, userCtrl.deleteUser); router.route("/delete").delete(authCtrl.requireLogin, userCtrl.deleteUser);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment