M-Gabrielly b577a418e1 feat(auth): Creates user in patient registration
- Adds automatic user creation in the new patient registration flow.              - To avoid merge conflicts, the user and profile APIs have been separated from the main lib/api.ts file.
2025-09-30 12:01:37 -03:00

64 lines
2.3 KiB
TypeScript

import {
API_BASE,
headers,
logAPI,
parse,
} from "../api";
import type { ApiOk } from "../api";
//
// Perfis de Usuário (Profiles)
//
export type UserProfile = {
id: string;
full_name?: string;
email?: string;
phone?: string;
avatar_url?: string;
disabled?: boolean;
created_at?: string;
updated_at?: string;
};
export type UserProfileInput = {
full_name?: string;
email?: string;
phone?: string;
avatar_url?: string;
disabled?: boolean;
};
export async function listarPerfis(params?: { page?: number; limit?: number; q?: string }): Promise<UserProfile[]> {
const query = new URLSearchParams();
if (params?.page) query.set("page", String(params.page));
if (params?.limit) query.set("limit", String(params.limit));
if (params?.q) query.set("q", params.q);
const url = `${API_BASE}/rest/v1/profiles${query.toString() ? `?${query.toString()}` : ""}`;
const res = await fetch(url, { method: "GET", headers: headers("json") });
const data = await parse<ApiOk<UserProfile[]>>(res);
logAPI("listarPerfis", { url, result: data });
return data?.data ?? (data as any);
}
export async function buscarPerfilPorId(id: string | number): Promise<UserProfile> {
const url = `${API_BASE}/rest/v1/profiles?id=eq.${id}`;
const res = await fetch(url, { method: "GET", headers: headers("json") });
// A API da Supabase/PostgREST retorna um array mesmo pedindo um ID, então pegamos o primeiro.
const data = await parse<UserProfile[]>(res);
const profile = data[0];
logAPI("buscarPerfilPorId", { url, result: profile });
return profile;
}
export async function atualizarPerfil(id: string | number, input: UserProfileInput): Promise<UserProfile> {
const url = `${API_BASE}/rest/v1/profiles?id=eq.${id}`;
const res = await fetch(url, { method: "PATCH", headers: headers("json"), body: JSON.stringify(input) });
// O método PATCH no PostgREST retorna um array vazio por padrão. Para retornar os dados, precisa de um header `Prefer: return=representation`
// Por simplicidade, vamos assumir que se não deu erro, a operação foi um sucesso.
// Se a API estiver configurada para retornar o objeto, o parse vai funcionar.
const data = await parse<ApiOk<UserProfile>>(res);
logAPI("atualizarPerfil", { url, payload: input, result: data });
return data?.data ?? (data as any);
}