Files
Investidor-V2/resources/js/lib/profile-json.ts
T
nala 01405cbf8a
tests / ci (push) Canceled after 0s
oportunidades 5
2026-10-10 14:15:28 +02:00

39 lines
1.2 KiB
TypeScript

export class ProfileValidationError extends Error {
constructor(
message: string,
public readonly fields: Record<string, string>,
) {
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)) : '',
},
body: method === 'GET' ? undefined : 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),
]),
),
);
return result;
}