From 2c3ee6aeae425130c81a4ccf8759b0cecba04790 Mon Sep 17 00:00:00 2001 From: Matheus Albino Brunhara Date: Sat, 28 May 2022 11:47:58 -0500 Subject: [PATCH] =?UTF-8?q?Refatorando=20c=C3=B3digo=20e=20corre=C3=A7?= =?UTF-8?q?=C3=B5es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/App.tsx | 17 ++++- src/pages/Perfil.tsx | 69 ++++++++++--------- .../sessionsService.ts} | 6 +- src/services/functions/usersService.ts | 53 ++++++++++++++ src/services/users/getById.ts | 35 ---------- 5 files changed, 110 insertions(+), 70 deletions(-) rename src/services/{refreshSession.ts => functions/sessionsService.ts} (84%) create mode 100644 src/services/functions/usersService.ts delete mode 100644 src/services/users/getById.ts diff --git a/src/App.tsx b/src/App.tsx index 2d5a17b..d2d3f4d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -39,6 +39,8 @@ import { search, home, person } from 'ionicons/icons'; import { useState, useContext, useEffect } from 'react'; import React from 'react'; +import sessionsService from './services/functions/sessionsService' + setupIonicReact(); const routes = ( @@ -69,8 +71,19 @@ const IonicApp: React.FC = () => { user.setIsLoggedIn = setIsLoggedIn; useEffect(() => { - // TODO, verifica se usuário está logado - // fazer com serviço externo (evita duplicações) + const verifyAuthenticatedUser = async () => { + const refreshSessionRes = await sessionsService.refreshSession() + + if (refreshSessionRes.error) { + return + } + + if (refreshSessionRes.userId) { + setIsLoggedIn(true) + } + } + + verifyAuthenticatedUser() }) return( diff --git a/src/pages/Perfil.tsx b/src/pages/Perfil.tsx index 7c6c7f3..484f67e 100644 --- a/src/pages/Perfil.tsx +++ b/src/pages/Perfil.tsx @@ -7,7 +7,6 @@ import { IonContent, IonFab, IonFabButton, - IonGrid, IonHeader, IonIcon, IonItem, @@ -24,12 +23,11 @@ import React, { useState, useEffect, useReducer } from "react"; import { IonRow, IonCol } from "@ionic/react"; import { createOutline } from "ionicons/icons"; -import * as sessionRoutes from '../services/api/session'; -import * as usersRoutes from '../services/api/users'; - import './Perfil.css' import LocalStorage from "../LocalStorage"; -import { refreshSession } from "../services/refreshSession"; + +import sessionsService from '../services/functions/sessionsService' +import usersService from '../services/functions/usersService' const Perfil: React.FC = () => { const [showToast, setShowToast] = useState(false); @@ -48,50 +46,56 @@ const Perfil: React.FC = () => { const history = useHistory(); + const redirectUserToLogin = () => { + // TODO, não impede o usuário de retornar a página de login + history.push({ pathname: '/login' }); + setMessageToast("Por favor, autentique-se!"); + setShowToast(true); + } + useEffect(() => { - const redirectUserToLogin = () => { - // TODO, não impede o usuário de retornar a página de login - history.push({ pathname: '/login' }); - setMessageToast("Por favor, autentique-se!"); - setShowToast(true); - } - const loadUserData = async () => { let userId = '' - + // verify if user is authenticated - const refreshSessionRes = await refreshSession() - + const refreshSessionRes = await sessionsService.refreshSession() + if (refreshSessionRes.error) { redirectUserToLogin() return } - + if (refreshSessionRes.userId) { userId = refreshSessionRes.userId } // get user info by ID - const getByIdRes = await usersRoutes.getById(userId) - + const getByIdRes = await usersService.getById(userId) + if (getByIdRes.error) { - setMessageToast(getByIdRes.message.data) + setMessageToast(getByIdRes.error.errorMessage) setShowToast(true) - + return } - - const userData = getByIdRes.data - - setInputValues({ - 'name': userData.name, - 'lastname': userData.lastname, - 'email': userData.email, - 'birth_date': userData.birth_date, - 'bio': userData.bio - }); + + if (getByIdRes.userData) { + const userData = getByIdRes.userData + + if (isMounted) { + setInputValues({ + 'name': userData.name, + 'lastname': userData.lastname, + 'email': userData.email, + 'birth_date': userData.birth_date, + 'bio': userData.bio + }); + } + } } + let isMounted = true; + const userToken = LocalStorage.getToken() if (!userToken) { @@ -99,7 +103,10 @@ const Perfil: React.FC = () => { } loadUserData() - }, [history]); + + return () => { isMounted = false }; + }, []); + // }, [history]); return ( diff --git a/src/services/refreshSession.ts b/src/services/functions/sessionsService.ts similarity index 84% rename from src/services/refreshSession.ts rename to src/services/functions/sessionsService.ts index 7d29d42..5685c19 100644 --- a/src/services/refreshSession.ts +++ b/src/services/functions/sessionsService.ts @@ -1,4 +1,4 @@ -import * as sessionRoutes from "../services/api/session"; +import * as sessionRoutes from "../api/session"; interface refreshSessionReturn { userId?: string; @@ -12,7 +12,7 @@ interface refreshSessionResponse { userId?: string; } -export const refreshSession = async (): Promise => { +const refreshSession = async (): Promise => { try { let res: refreshSessionResponse = await sessionRoutes.refresh() @@ -42,3 +42,5 @@ export const refreshSession = async (): Promise => { // } // } }; + +export default { refreshSession } \ No newline at end of file diff --git a/src/services/functions/usersService.ts b/src/services/functions/usersService.ts new file mode 100644 index 0000000..4bb9a56 --- /dev/null +++ b/src/services/functions/usersService.ts @@ -0,0 +1,53 @@ +import * as usersRoutes from "../api/users"; + +interface getByIdReturn { + userData?: { + name: string; + lastname: string; + email: string; + birth_date: string; + bio: string; + }, + error?: { + errorMessage: string; + } +} + +interface getByIdRes { + status: string; + message: string; + userId?: string; + data: { + name: string; + lastname: string; + email: string; + birth_date: string; + bio: string; + }, +} + +const getById = async (userId: string): Promise => { + try { + let res: getByIdRes = await usersRoutes.getById(userId) + + if (res.status === "error") { + return { + error: { + errorMessage: res.message, + } + }; + } + + return { + userData: res.data, + }; + } catch(err) { + return { + error: { + errorMessage: "Por favor, autentique-se.", + } + }; + } +}; + +export default { getById } \ No newline at end of file diff --git a/src/services/users/getById.ts b/src/services/users/getById.ts deleted file mode 100644 index 9ea9a5c..0000000 --- a/src/services/users/getById.ts +++ /dev/null @@ -1,35 +0,0 @@ -import * as usersRoutes from "../../services/api/users"; - -interface getByIdReturn { - userId?: string; - error?: boolean; - errorMessage?: string; -} - -interface getByIdResponse { - status?: string; - message?: string; - userId?: string; -} - -export const getById = async (userId: string): Promise => { - try { - let res: getByIdResponse = await usersRoutes.getById(userId) - - if (res.status === "error") { - return { - error: true, - errorMessage: res.message, - }; - } - - return { - userId: res.userId, - }; - } catch(err) { - return { - error: true, - errorMessage: "Por favor, autentique-se.", - }; - } -};