Files
Investidor-V2/resources/js/lib/profile-json.ts
T
nala c13f250b87
tests / ci (push) Canceled after 0s
versao compilada
2026-10-15 17:37:00 +02:00

41 lines
1.3 KiB
TypeScript

export class ProfileValidationError extends Error {
constructor(
message: string,
public readonly fields: Record<string, string>,
public readonly reauthenticate = false,
) {
super(message);
}
}
export async function profileJson(
url: string,
data: object = {},
method: 'GET' | 'POST' = 'POST',
) {
const cookie = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='));
const response = await fetch(url, {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': cookie ? decodeURIComponent(cookie.slice(11)) : '',
},
...(method === 'GET' ? {} : { body: JSON.stringify(data) }),
});
const result = await response.json();
if (!response.ok)
throw new ProfileValidationError(
result.message ?? 'A ação não foi concluída.',
Object.fromEntries(
Object.entries(result.errors ?? {}).map(([key, value]) => [
key,
Array.isArray(value) ? value.join(' ') : String(value),
]),
),
response.headers.get('X-Portal-Reauthentication') === 'required',
);
return result;
}