uhr/src/cookie-handler.ts

82 lines
2.4 KiB
TypeScript

/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import * as Cookies from 'js-cookie';
export class CookieHandler {
public constructor(private readonly widgetId: string, private readonly cookiePath?: string) {
}
public getLayout(): string {
const oldCookie = this.getCookie('uhr-language');
if (oldCookie) {
// aha, old cookie is set. migrate to new one!
this.removeCookie('uhr-language');
this.setLayout(oldCookie);
}
return this.getCookie('uhr-layout');
}
public setLayout(layout: string): void {
this.setCookie('uhr-layout', layout);
}
public getMode(): string {
return this.getCookie('uhr-mode');
}
public setMode(mode: string): void {
this.setCookie('uhr-mode', mode);
}
public getStatus(): string {
return this.getCookie('uhr-status');
}
public setStatus(status: string): void {
this.setCookie('uhr-status', status);
}
public getTheme(): string {
return this.getCookie('uhr-theme');
}
public setTheme(theme: string): void {
this.setCookie('uhr-theme', theme);
}
private getCookie(cookieName: string): string {
return Cookies.get(cookieName + this.widgetId);
}
private setCookie(cookieName: string, cookieValue: string): void {
let options;
if (this.cookiePath) {
options = {expires: 365, path: this.cookiePath};
} else {
options = {expires: 365};
}
Cookies.set(cookieName + this.widgetId, cookieValue, options);
}
private removeCookie(cookieName: string): void {
if (this.cookiePath) {
Cookies.remove(cookieName + this.widgetId, {path: this.cookiePath});
} else {
Cookies.remove(cookieName + this.widgetId);
}
}
}