Cookie gestion + UserStore editing cookies
This commit is contained in:
parent
91d1c0b5e8
commit
a2b3c15933
44
src/front/Services/CookieService/CookieService.ts
Normal file
44
src/front/Services/CookieService/CookieService.ts
Normal file
@ -0,0 +1,44 @@
|
||||
export default class CookieService {
|
||||
private static instance: CookieService;
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance() {
|
||||
return (this.instance ??= new this());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description : set a cookie with a name and a value that expire in 7 days
|
||||
* @throws {Error} If the name or the value is empty
|
||||
*/
|
||||
public setCookie(name: string, value: string) {
|
||||
if (!name || !value) throw new Error("Cookie name or value is empty");
|
||||
const date = new Date();
|
||||
|
||||
// Set it expire in 7 days
|
||||
date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Set it
|
||||
document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/";
|
||||
}
|
||||
|
||||
public getCookie(name: string) {
|
||||
const value = "; " + document.cookie;
|
||||
const parts = value.split("; " + name + "=");
|
||||
|
||||
if (parts.length == 2) {
|
||||
return parts.pop()!.split(";").shift();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
public deleteCookie(name: string) {
|
||||
const date = new Date();
|
||||
|
||||
// Set it expire in -1 days
|
||||
date.setTime(date.getTime() + -1 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Set it
|
||||
document.cookie = name + "=; expires=" + date.toUTCString() + "; path=/";
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user