45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import z from "zod";
|
|
import ProfileContentManager from "./base.ts";
|
|
|
|
export enum ProfileSetting {
|
|
Test = "test"
|
|
}
|
|
|
|
const genericSettingSchema = z.object({
|
|
Key: z.string(),
|
|
Value: z.string()
|
|
});
|
|
const settingsSchema = z.array(genericSettingSchema);
|
|
type Setting = z.infer<typeof genericSettingSchema>;
|
|
|
|
export class ProfileSettingsManager extends ProfileContentManager {
|
|
|
|
static settingsKey = "settings";
|
|
#key = this.profile.constructProfilePropertyKey(ProfileSettingsManager.settingsKey);
|
|
|
|
async getAllSettings(): Promise<Setting[]> {
|
|
const items = await this.kv.getKv().get(this.#key);
|
|
if (items.value == null) return [];
|
|
const parsed = settingsSchema.safeParse(items.value);
|
|
if (parsed.success) return parsed.data;
|
|
else return [];
|
|
}
|
|
|
|
async getSetting(setting: ProfileSetting) {
|
|
const settings = await this.getAllSettings();
|
|
return settings.find(s => s.Key == setting)?.Value || null;
|
|
}
|
|
|
|
async #updateSettings(settings: Setting[]) {
|
|
await this.kv.getKv().set(this.#key, settings);
|
|
}
|
|
|
|
async setSetting(Key: ProfileSetting, Value: string) {
|
|
const settings = await this.getAllSettings();
|
|
const s = settings.find(setting => setting.Key === Key);
|
|
if (!s) settings.push({ Key, Value });
|
|
else s.Value = Value;
|
|
await this.#updateSettings(settings);
|
|
}
|
|
|
|
} |