commit16
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user