diff --git a/src/front/Services/CookieService/CookieService.ts b/src/front/Services/CookieService/CookieService.ts new file mode 100644 index 00000000..0f2f33cc --- /dev/null +++ b/src/front/Services/CookieService/CookieService.ts @@ -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=/"; + } +}