main atualizada
This commit is contained in:
parent
5b280c7d31
commit
2dc3188903
111
services/api.mjs
111
services/api.mjs
@ -1,14 +1,18 @@
|
|||||||
// Caminho: [seu-caminho]/services/api.mjs
|
// Caminho: services/api.mjs
|
||||||
|
|
||||||
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||||||
const API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
const API_KEY =
|
||||||
|
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
||||||
|
|
||||||
|
export const apikey = API_KEY;
|
||||||
|
|
||||||
|
// --- LOGIN COM EMAIL E SENHA ---
|
||||||
export async function loginWithEmailAndPassword(email, password) {
|
export async function loginWithEmailAndPassword(email, password) {
|
||||||
const response = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
|
const response = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"apikey": API_KEY,
|
apikey: API_KEY,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ email, password }),
|
body: JSON.stringify({ email, password }),
|
||||||
});
|
});
|
||||||
@ -19,47 +23,14 @@ export async function loginWithEmailAndPassword(email, password) {
|
|||||||
throw new Error(data.error_description || "Credenciais inválidas.");
|
throw new Error(data.error_description || "Credenciais inválidas.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.access_token && typeof window !== 'undefined') {
|
if (data.access_token && typeof window !== "undefined") {
|
||||||
// Padronizando para salvar o token no localStorage
|
|
||||||
localStorage.setItem("token", data.access_token);
|
localStorage.setItem("token", data.access_token);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- NOVA FUNÇÃO DE LOGOUT CENTRALIZADA ---
|
// --- LOGIN PADRÃO AUTOMÁTICO ---
|
||||||
async function logout() {
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
if (!token) return; // Se não há token, não há o que fazer
|
|
||||||
|
|
||||||
try {
|
|
||||||
await fetch(`${BASE_URL}/auth/v1/logout`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"apikey": API_KEY,
|
|
||||||
"Authorization": `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
// Mesmo que a chamada falhe, o logout no cliente deve continuar.
|
|
||||||
// O token pode já ter expirado no servidor, por exemplo.
|
|
||||||
console.error("Falha ao invalidar token no servidor (isso pode ser normal se o token já expirou):", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function request(endpoint, options = {}) {
|
|
||||||
const token = typeof window !== 'undefined' ? localStorage.getItem("token") : null;
|
|
||||||
|
|
||||||
const headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"apikey": API_KEY,
|
|
||||||
...(token ? { "Authorization": `Bearer ${token}` } : {}),
|
|
||||||
...options.headers,
|
|
||||||
};
|
|
||||||
const API_KEY =
|
|
||||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
|
||||||
|
|
||||||
export const apikey = API_KEY;
|
|
||||||
let loginPromise = null;
|
let loginPromise = null;
|
||||||
|
|
||||||
export async function login() {
|
export async function login() {
|
||||||
@ -93,6 +64,30 @@ export async function login() {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- LOGOUT CENTRALIZADO ---
|
||||||
|
async function logout() {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fetch(`${BASE_URL}/auth/v1/logout`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
apikey: API_KEY,
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
"Falha ao invalidar token no servidor (pode já estar expirado):",
|
||||||
|
error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- FUNÇÃO CENTRAL DE REQUISIÇÕES ---
|
||||||
async function request(endpoint, options = {}) {
|
async function request(endpoint, options = {}) {
|
||||||
if (!loginPromise) loginPromise = login();
|
if (!loginPromise) loginPromise = login();
|
||||||
|
|
||||||
@ -125,7 +120,7 @@ async function request(endpoint, options = {}) {
|
|||||||
? `${BASE_URL}${endpoint}`
|
? `${BASE_URL}${endpoint}`
|
||||||
: `${BASE_URL}/rest/v1${endpoint}`;
|
: `${BASE_URL}/rest/v1${endpoint}`;
|
||||||
|
|
||||||
console.log("🌐 Requisição para:", fullUrl, "com headers:", headers);
|
console.log("🌐 Requisição para:", fullUrl);
|
||||||
|
|
||||||
const response = await fetch(fullUrl, {
|
const response = await fetch(fullUrl, {
|
||||||
...options,
|
...options,
|
||||||
@ -136,46 +131,28 @@ async function request(endpoint, options = {}) {
|
|||||||
let errorBody;
|
let errorBody;
|
||||||
try {
|
try {
|
||||||
errorBody = await response.json();
|
errorBody = await response.json();
|
||||||
} catch (e) {
|
} catch {
|
||||||
errorBody = await response.text();
|
errorBody = await response.text();
|
||||||
}
|
}
|
||||||
throw new Error(`Erro HTTP: ${response.status} - ${JSON.stringify(errorBody)}`);
|
throw new Error(`Erro HTTP: ${response.status} - ${JSON.stringify(errorBody)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.status === 204) return {};
|
if (response.status === 204) return {};
|
||||||
return await response.json();
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro na requisição:", error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adicionamos a função de logout ao nosso objeto de API exportado
|
|
||||||
export const api = {
|
|
||||||
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
|
|
||||||
post: (endpoint, data, options) => request(endpoint, { method: "POST", body: JSON.stringify(data), ...options }),
|
|
||||||
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
|
|
||||||
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
|
|
||||||
logout: logout, // <-- EXPORTANDO A NOVA FUNÇÃO
|
|
||||||
};
|
|
||||||
if (!response.ok) {
|
|
||||||
const msg = await response.text();
|
|
||||||
console.error("❌ Erro HTTP:", response.status, msg);
|
|
||||||
throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${msg}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const contentType = response.headers.get("content-type");
|
const contentType = response.headers.get("content-type");
|
||||||
if (!contentType || !contentType.includes("application/json")) return {};
|
if (!contentType || !contentType.includes("application/json")) return {};
|
||||||
|
|
||||||
return await response.json();
|
return await response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- EXPORTANDO OBJETO API ---
|
||||||
export const api = {
|
export const api = {
|
||||||
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
|
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
|
||||||
post: (endpoint, data) =>
|
post: (endpoint, data, options) =>
|
||||||
request(endpoint, { method: "POST", body: JSON.stringify(data) }),
|
request(endpoint, { method: "POST", body: JSON.stringify(data), ...options }),
|
||||||
patch: (endpoint, data) =>
|
patch: (endpoint, data, options) =>
|
||||||
request(endpoint, { method: "PATCH", body: JSON.stringify(data) }),
|
request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
|
||||||
delete: (endpoint) => request(endpoint, { method: "DELETE" }),
|
delete: (endpoint, options) =>
|
||||||
|
request(endpoint, { method: "DELETE", ...options }),
|
||||||
|
logout,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user