diff --git a/client/src/app/[lang]/(user)/user/profile/page.tsx b/client/src/app/[lang]/(user)/user/profile/page.tsx index 5af75f5..78b055e 100644 --- a/client/src/app/[lang]/(user)/user/profile/page.tsx +++ b/client/src/app/[lang]/(user)/user/profile/page.tsx @@ -56,6 +56,7 @@ export default function Profile({ .push(`users/update`, formData, undefined, true); if (response.status === 'success') { setMessage(response.message); + location.reload(); } } catch (e: any) { checkErrors(e.response.data); diff --git a/server/src/user/service/user.service.ts b/server/src/user/service/user.service.ts index 64af340..dd17c82 100644 --- a/server/src/user/service/user.service.ts +++ b/server/src/user/service/user.service.ts @@ -1,11 +1,11 @@ import { Prisma, PrismaClient, User } from '@prisma/client'; -import fs from 'fs-extra'; import { IUser } from '../../types/user'; import AppError from '../../utils/appError'; import { signJwt } from '../../utils/jwt'; import { IUserUpdateDto, UserDto } from '../dto/user.dto'; import { UserRepository } from '../repository/user.repository'; import { File } from '../../types/file'; +import { removeExistingImages } from '../../utils/removeExistingImages'; export const createUser = async (user: UserDto) => { return await UserRepository.createUser(user); }; @@ -117,11 +117,28 @@ export async function updateUser({ avatar: null, }; try { - if (!avatar) { + const userHasImage = await UserRepository.findByUserId(user.id); + + if (!avatar && !userHasImage!.avatar) { userUpdate.avatar = user.avatar; - await UserRepository.updateUser(userUpdate); } - // TODO: Logic if user change avatar + + if (!avatar && userHasImage!.avatar) { + userUpdate.avatar = userHasImage!.avatar; + } + + if (avatar && !userHasImage!.avatar) { + userUpdate.avatar = avatar.filename; + } + + if (avatar && userHasImage!.avatar) { + userUpdate.avatar = avatar.filename; + await removeExistingImages({ + filename: userHasImage!.avatar, + environment: process.env.NODE_ENV, + }); + } + await UserRepository.updateUser(userUpdate); } catch (err: any) { console.error(err); throw new AppError(400, 'Erreur lors de la mise à jour du profil.'); diff --git a/server/src/utils/removeExistingImages.ts b/server/src/utils/removeExistingImages.ts new file mode 100644 index 0000000..ff94a1c --- /dev/null +++ b/server/src/utils/removeExistingImages.ts @@ -0,0 +1,18 @@ +import fs from 'fs-extra'; + +export const removeExistingImages = async ({ + filename, + environment, +}: { + filename: string; + environment: string; +}) => { + if (environment === 'production') { + const path = `dist/public/uploads/${filename}`; + await fs.unlink(path); + } + if (environment === 'development') { + const path = `public/uploads/${filename}`; + await fs.unlink(path); + } +};