This commit is contained in:
2026-11-02 20:31:15 +02:00
parent 8ddfa93f45
commit 1da273f1f3
131 changed files with 14802 additions and 526 deletions
+31 -9
View File
@@ -12,29 +12,51 @@ export async function profileJson(
data: object = {},
method: 'GET' | 'POST' = 'POST',
) {
const cookie = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='));
let token = '';
if (method !== 'GET') {
const cookie =
typeof document === 'undefined'
? undefined
: document.cookie
.split(';')
.map((value) => value.trim())
.find((value) => value.startsWith('XSRF-TOKEN='));
try {
token = cookie ? decodeURIComponent(cookie.slice(11)) : '';
} catch {
throw new ProfileValidationError(
'A sessão não pôde ser validada. Actualize a página e tente novamente.',
{},
);
}
}
const response = await fetch(url, {
method,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': cookie ? decodeURIComponent(cookie.slice(11)) : '',
...(method === 'GET' ? {} : { 'X-XSRF-TOKEN': token }),
},
...(method === 'GET' ? {} : { body: JSON.stringify(data) }),
});
const result = await response.json();
if (!response.ok)
const result = await response.json().catch(() => null);
const reauthenticate =
response.headers.get('X-Portal-Reauthentication') === 'required';
if (!response.ok || (result === null && response.status !== 204))
throw new ProfileValidationError(
result.message ?? 'A ação não foi concluída.',
typeof result?.message === 'string'
? result.message
: response.status === 419
? 'A sessão expirou. Actualize a página e tente novamente.'
: 'A ação não foi concluída. Tente novamente.',
Object.fromEntries(
Object.entries(result.errors ?? {}).map(([key, value]) => [
Object.entries(result?.errors ?? {}).map(([key, value]) => [
key,
Array.isArray(value) ? value.join(' ') : String(value),
]),
),
response.headers.get('X-Portal-Reauthentication') === 'required',
reauthenticate,
);
return result;
}