42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
export interface SettingRow {
|
|
key: string;
|
|
value: string;
|
|
}
|
|
|
|
export type SettingsFetcher = () => Promise<SettingRow[]>;
|
|
|
|
/**
|
|
* Mirrors Laravel's App\Services\SettingsService: loads the whole
|
|
* website_settings table into a key->value map, caches it in-process,
|
|
* and reads with a default fallback. Booleans are stored as '1'/'0'.
|
|
*/
|
|
export class SettingsService {
|
|
private cache: Map<string, string> | null = null;
|
|
|
|
constructor(private readonly fetcher: SettingsFetcher) {}
|
|
|
|
private async load(): Promise<Map<string, string>> {
|
|
if (this.cache === null) {
|
|
const rows = await this.fetcher();
|
|
this.cache = new Map(rows.map((r) => [r.key, r.value]));
|
|
}
|
|
return this.cache;
|
|
}
|
|
|
|
async get(key: string, def: string | null = null): Promise<string | null> {
|
|
const map = await this.load();
|
|
return map.has(key) ? (map.get(key) as string) : def;
|
|
}
|
|
|
|
async getBool(key: string, def = false): Promise<boolean> {
|
|
const map = await this.load();
|
|
if (!map.has(key)) return def;
|
|
const v = (map.get(key) as string).toLowerCase();
|
|
return v === "1" || v === "true";
|
|
}
|
|
|
|
clear(): void {
|
|
this.cache = null;
|
|
}
|
|
}
|