export class ProfileValidationError extends Error { constructor( message: string, public readonly fields: Record, 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; }