user_atualizado
This commit is contained in:
parent
6d1f889397
commit
02d8a5b5d7
@ -1,8 +1,36 @@
|
|||||||
|
// Caminho: services/api.mjs
|
||||||
|
|
||||||
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||||||
const API_KEY =
|
const API_KEY =
|
||||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
||||||
|
|
||||||
export const apikey = API_KEY;
|
export const apikey = API_KEY;
|
||||||
|
|
||||||
|
// --- LOGIN COM EMAIL E SENHA ---
|
||||||
|
export async function loginWithEmailAndPassword(email, password) {
|
||||||
|
const response = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
apikey: API_KEY,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.error_description || "Credenciais inválidas.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.access_token && typeof window !== "undefined") {
|
||||||
|
localStorage.setItem("token", data.access_token);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- LOGIN PADRÃO AUTOMÁTICO ---
|
||||||
let loginPromise = null;
|
let loginPromise = null;
|
||||||
|
|
||||||
export async function login() {
|
export async function login() {
|
||||||
@ -36,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();
|
||||||
|
|
||||||
@ -64,11 +116,9 @@ async function request(endpoint, options = {}) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const fullUrl =
|
const fullUrl =
|
||||||
endpoint.startsWith("/rest/v1") || endpoint.startsWith("/functions/")
|
endpoint.startsWith("/") ? `${BASE_URL}${endpoint}` : `${BASE_URL}/rest/v1/${endpoint}`;
|
||||||
? `${BASE_URL}${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,
|
||||||
@ -76,22 +126,31 @@ async function request(endpoint, options = {}) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const msg = await response.text();
|
let errorBody;
|
||||||
console.error("❌ Erro HTTP:", response.status, msg);
|
try {
|
||||||
throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${msg}`);
|
errorBody = await response.json();
|
||||||
|
} catch {
|
||||||
|
errorBody = await response.text();
|
||||||
|
}
|
||||||
|
throw new Error(`Erro HTTP: ${response.status} - ${JSON.stringify(errorBody)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (response.status === 204) return {};
|
||||||
|
|
||||||
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,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,7 @@ import { api } from "./api.mjs";
|
|||||||
export const doctorsService = {
|
export const doctorsService = {
|
||||||
list: () => api.get("/rest/v1/doctors"),
|
list: () => api.get("/rest/v1/doctors"),
|
||||||
getById: (id) => api.get(`/rest/v1/doctors?id=eq.${id}`).then(data => data[0]),
|
getById: (id) => api.get(`/rest/v1/doctors?id=eq.${id}`).then(data => data[0]),
|
||||||
create: (data) => api.post("/rest/v1/doctors", data),
|
create: (data) => api.post("/functions/v1/create-doctor", data),
|
||||||
update: (id, data) => api.patch(`/rest/v1/doctors?id=eq.${id}`, data),
|
update: (id, data) => api.patch(`/rest/v1/doctors?id=eq.${id}`, data),
|
||||||
delete: (id) => api.delete(`/rest/v1/doctors?id=eq.${id}`),
|
delete: (id) => api.delete(`/rest/v1/doctors?id=eq.${id}`),
|
||||||
};
|
};
|
||||||
@ -8,7 +8,8 @@ export const usersService = {
|
|||||||
|
|
||||||
async create_user(data) {
|
async create_user(data) {
|
||||||
// continua usando a Edge Function corretamente
|
// continua usando a Edge Function corretamente
|
||||||
return await api.post(`/functions/v1/user-create`, data);
|
return await api.post(`/functions/v1/create-user-with-password
|
||||||
|
`, data);
|
||||||
},
|
},
|
||||||
|
|
||||||
// 🚀 Busca dados completos do usuário direto do banco
|
// 🚀 Busca dados completos do usuário direto do banco
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user