2025-10-21 13:02:56 -03:00

156 lines
4.0 KiB
TypeScript

/**
* Netlify Function: Profiles
* GET /rest/v1/profiles - Lista perfis
* GET /rest/v1/profiles/{id} - Busca por ID
* PATCH /rest/v1/profiles/{id} - Atualiza avatar_url
*/
import type { Handler, HandlerEvent } from "@netlify/functions";
const SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
const SUPABASE_ANON_KEY =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
export const handler: Handler = async (event: HandlerEvent) => {
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Methods": "GET, PATCH, OPTIONS",
};
if (event.httpMethod === "OPTIONS") {
return {
statusCode: 200,
headers,
body: "",
};
}
try {
const authHeader =
event.headers.authorization || event.headers.Authorization;
if (!authHeader) {
return {
statusCode: 401,
headers,
body: JSON.stringify({ error: "Token não fornecido" }),
};
}
// Extrai ID da URL se houver
const pathParts = event.path.split("/");
const profileId =
pathParts[pathParts.length - 1] !== "profiles"
? pathParts[pathParts.length - 1]
: null;
// GET - Listar ou buscar por ID
if (event.httpMethod === "GET") {
let url = `${SUPABASE_URL}/rest/v1/profiles`;
if (profileId && profileId !== "profiles") {
url += `?id=eq.${profileId}&select=*`;
} else if (event.queryStringParameters) {
const params = new URLSearchParams(
event.queryStringParameters as Record<string, string>
);
url += `?${params.toString()}`;
if (!params.has("select")) {
url += url.includes("?") ? "&select=*" : "?select=*";
}
} else {
url += "?select=*";
}
const response = await fetch(url, {
method: "GET",
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: authHeader,
},
});
let data = await response.json();
if (
profileId &&
profileId !== "profiles" &&
Array.isArray(data) &&
data.length > 0
) {
data = data[0];
}
return {
statusCode: response.status,
headers: {
...headers,
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
}
// PATCH - Atualizar avatar_url
if (event.httpMethod === "PATCH") {
if (!profileId || profileId === "profiles") {
return {
statusCode: 400,
headers,
body: JSON.stringify({ error: "ID do perfil é obrigatório" }),
};
}
const body = JSON.parse(event.body || "{}");
const response = await fetch(
`${SUPABASE_URL}/rest/v1/profiles?id=eq.${profileId}`,
{
method: "PATCH",
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: authHeader,
"Content-Type": "application/json",
Prefer: "return=representation",
},
body: JSON.stringify(body),
}
);
let data = await response.json();
if (Array.isArray(data) && data.length > 0) {
data = data[0];
}
return {
statusCode: response.status,
headers: {
...headers,
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
}
return {
statusCode: 405,
headers,
body: JSON.stringify({ error: "Method Not Allowed" }),
};
} catch (error) {
console.error("Erro na API de perfis:", error);
return {
statusCode: 500,
headers,
body: JSON.stringify({
error: "Erro interno no servidor",
message: error instanceof Error ? error.message : "Erro desconhecido",
}),
};
}
};