From f0f15672979ad2452aa26e8798af375f3c7de282 Mon Sep 17 00:00:00 2001 From: Vinicius Souza Date: Thu, 7 Nov 2024 15:35:00 +0000 Subject: [PATCH] feat: upload photo --- src/screens/Profile.tsx | 31 +++++++++++++++++++++++++++++-- src/utils/Slug.ts | 10 ++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 src/utils/Slug.ts diff --git a/src/screens/Profile.tsx b/src/screens/Profile.tsx index f725291..357587c 100644 --- a/src/screens/Profile.tsx +++ b/src/screens/Profile.tsx @@ -8,6 +8,8 @@ import { Controller, useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import { api } from '@services/api'; +import { AppError } from '@utils/AppError'; +import { slug } from '@utils/Slug'; import { useAuth } from '@hooks/useAuth'; @@ -16,7 +18,6 @@ import { Input } from '@components/Input'; import { ScreenHeader } from '@components/ScreenHeader'; import { UserPhoto } from '@components/UserPhoto'; import { ToastMessage } from '@components/ToastMessage'; -import { AppError } from '@utils/AppError'; type ProfileForm = { name: string; @@ -150,7 +151,33 @@ export function Profile() { }); } - setUserPhoto(photoURI); + const fileExtension = photoSelection.assets[0].uri.split('.').pop(); + const photoFile = { + name: `${slug(user.name)}.${fileExtension}`.toLowerCase(), + uri: photoSelection.assets[0].uri, + type: `${photoSelection.assets[0].type}/${fileExtension}`, + } as any; + + const userPhotoUploadForm = new FormData(); + userPhotoUploadForm.append('avatar', photoFile); + + await api.patch('/users/avatar', userPhotoUploadForm, { + headers: { + 'Content-Type': 'multipart/form-data', + }, + }); + + toast.show({ + placement: 'top', + render: ({ id }) => ( + toast.close(id)} + /> + ), + }); } } catch (error) { console.error(error); diff --git a/src/utils/Slug.ts b/src/utils/Slug.ts new file mode 100644 index 0000000..ab41bf3 --- /dev/null +++ b/src/utils/Slug.ts @@ -0,0 +1,10 @@ +export function slug(str: string): string { + return str + .normalize('NFD') // Normalize accented characters to decomposed form + .replace(/[\u0300-\u036f]/g, '') // Remove diacritic marks (accents) + .toLowerCase() // Convert to lowercase + .replace(/[^a-z0-9\s-]/g, '') // Remove non-alphanumeric characters except spaces and hyphens + .trim() // Remove leading and trailing spaces + .replace(/\s+/g, '-') // Replace spaces with hyphens + .replace(/-+/g, '-'); // Replace multiple hyphens with a single hyphen +}