feat: Aggiunti headers per le richieste dei models

È stata aggiunta la gestione dei cookie al modello Record per supportare l'uso dei token CSRF. Questa modifica consente al modello di ottenere il token CSRF dal tag meta o dal cookie, come specificato nella documentazione di Laravel.
This commit is contained in:
Maicol Battistini 2023-12-11 10:51:17 +01:00
parent 3f20852d01
commit c9a93976fa
No known key found for this signature in database
1 changed files with 15 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import {Attr, Model, SpraypaintBase} from 'spraypaint';
import {Cookies} from 'typescript-cookie';
@Model()
export default class Record extends SpraypaintBase {
@ -12,4 +13,18 @@ export default class Record extends SpraypaintBase {
isNew(): boolean {
return this.id === undefined;
}
static fetchOptions(): RequestInit {
// Get the CSRF token from the meta tag or the cookie
// https://laravel.com/docs/10.x/csrf#csrf-x-csrf-token
const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || Cookies.get('XSRF-TOKEN') as string;
return {
headers: {
'X-XSRF-TOKEN': token,
Accept: 'application/vnd.api+json',
'Content-Type': 'application/vnd.api+json'
}
};
}
}