@@ -0,0 +1,38 @@
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user