common-ui/src/lib/services/base-user-preference.service.ts
2022-07-25 17:46:17 +03:00

71 lines
2.1 KiB
TypeScript

import { Injectable } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { List, RequiredParam, Validate } from '../utils';
import { GenericService } from './generic.service';
export type UserAttributes = Record<string, List>;
const KEYS = {
language: 'Language',
theme: 'Theme',
} as const;
@Injectable()
export abstract class BaseUserPreferenceService extends GenericService<UserAttributes> {
protected abstract readonly _devFeaturesEnabledKey: string;
#userAttributes: UserAttributes = {};
get userAttributes(): UserAttributes {
return this.#userAttributes;
}
get areDevFeaturesEnabled(): boolean {
const value = sessionStorage.getItem(this._devFeaturesEnabledKey);
return value === 'true' ?? false;
}
getTheme(): string {
return this._getAttribute(KEYS.theme, 'light');
}
async saveTheme(theme: 'light' | 'dark'): Promise<void> {
await this._save(KEYS.theme, theme);
window.location.reload();
}
getLanguage(): string {
return this._getAttribute(KEYS.language);
}
async saveLanguage(language: string): Promise<void> {
await this._save(KEYS.language, language);
}
toggleDevFeatures(): void {
sessionStorage.setItem(this._devFeaturesEnabledKey, String(!this.areDevFeaturesEnabled));
window.location.reload();
}
async reload(): Promise<void> {
const attributes = await firstValueFrom(this.getAll<UserAttributes>());
this.#userAttributes = attributes ?? {};
}
@Validate()
savePreferences(@RequiredParam() body: List, @RequiredParam() key: string) {
return this._put(body, `${this._defaultModelPath}/${key}`);
}
protected async _save(key: string, value: string): Promise<void> {
this.userAttributes[key] = [value];
await firstValueFrom(this.savePreferences([value], key));
}
protected _getAttribute(key: string, defaultValue = ''): string {
if (this.userAttributes[key]?.length > 0) {
return this.userAttributes[key][0];
}
return defaultValue;
}
}