Tornando a função refreshSessions externa

This commit is contained in:
Matheus Albino Brunhara
2022-05-25 17:56:10 -05:00
parent 3c8e204339
commit f3969579f1
2 changed files with 52 additions and 12 deletions

View File

@@ -29,6 +29,7 @@ import * as usersRoutes from '../services/api/users';
import './Perfil.css' import './Perfil.css'
import LocalStorage from "../LocalStorage"; import LocalStorage from "../LocalStorage";
import { refreshSession } from "../services/refreshSession";
const Perfil: React.FC = () => { const Perfil: React.FC = () => {
const [showToast, setShowToast] = useState(false); const [showToast, setShowToast] = useState(false);
@@ -57,19 +58,14 @@ const Perfil: React.FC = () => {
const loadUserData = async () => { const loadUserData = async () => {
let userId = '' let userId = ''
await sessionRoutes.refresh().then(response => { // verify if user is authenticated
if (response.status === 'error') { const refreshedSession = await refreshSession()
setMessageToast(response.message);
setShowToast(true); if (refreshedSession.error) {
return
}
userId = response.userId
}).catch(() => {
redirectUserToLogin() redirectUserToLogin()
}) return
}
await usersRoutes.getById(userId).then(response => { await usersRoutes.getById(userId).then(response => {
if (response.status === 'error') { if (response.status === 'error') {

View File

@@ -0,0 +1,44 @@
import * as sessionRoutes from "../services/api/session";
interface refreshSessionReturn {
userId?: string;
error?: boolean;
errorMessage?: string;
}
interface refreshSessionResponse {
status?: string;
message?: string;
userId?: string;
}
export const refreshSession = async (): Promise<refreshSessionReturn> => {
try {
let res: refreshSessionResponse = await sessionRoutes.refresh()
if (res.status === "error") {
return {
error: true,
errorMessage: res.message,
};
}
return {
userId: res.userId,
};
} catch(err) {
return {
error: true,
errorMessage: "Por favor, autentique-se.",
};
}
// catch (err: any) {
// if (err.response) {
// // The client was given an error response (5xx, 4xx)
// } else if (err.request) {
// // The client never received a response, and the request was never left
// } else {
// // Anything else
// }
// }
};