diff options
| author | MohamedBassem <me@mbassem.com> | 2025-03-12 00:33:39 +0000 |
|---|---|---|
| committer | MohamedBassem <me@mbassem.com> | 2025-03-12 00:34:18 +0000 |
| commit | 7bffa02cf67bcdd99e6ed16728a1eb41790f3910 (patch) | |
| tree | babac3e928db21a0de369c46418f28cc75af87e0 | |
| parent | b8c587e3c3e717263da84522d59c7904715ae22a (diff) | |
| download | karakeep-7bffa02cf67bcdd99e6ed16728a1eb41790f3910.tar.zst | |
fix(extension): Fix handling for empty storage. #10
| -rw-r--r-- | apps/browser-extension/src/utils/settings.ts | 49 |
1 files changed, 36 insertions, 13 deletions
diff --git a/apps/browser-extension/src/utils/settings.ts b/apps/browser-extension/src/utils/settings.ts index 6d51acde..c273acfa 100644 --- a/apps/browser-extension/src/utils/settings.ts +++ b/apps/browser-extension/src/utils/settings.ts @@ -1,18 +1,24 @@ import React from "react"; +import { z } from "zod"; -export interface Settings { - apiKey: string; - apiKeyId?: string; - address: string; -} +const zSettingsSchema = z.object({ + apiKey: z.string(), + apiKeyId: z.string().optional(), + address: z.string(), +}); + +const DEFAULT_SETTINGS: Settings = { + apiKey: "", + address: "", +}; + +export type Settings = z.infer<typeof zSettingsSchema>; const STORAGE = chrome.storage.sync; export default function usePluginSettings() { - const [settings, setSettingsInternal] = React.useState<Settings>({ - apiKey: "", - address: "", - }); + const [settings, setSettingsInternal] = + React.useState<Settings>(DEFAULT_SETTINGS); const [isInit, setIsInit] = React.useState(false); @@ -29,7 +35,12 @@ export default function usePluginSettings() { if (changes.settings === undefined) { return; } - setSettingsInternal(changes.settings.newValue as Settings); + const parsedSettings = zSettingsSchema.safeParse( + changes.settings.newValue, + ); + if (parsedSettings.success) { + setSettingsInternal(parsedSettings.data); + } }; STORAGE.onChanged.addListener(onChange); return () => { @@ -46,16 +57,28 @@ export default function usePluginSettings() { } export async function getPluginSettings() { - return (await STORAGE.get("settings")).settings as Settings; + const parsedSettings = zSettingsSchema.safeParse( + (await STORAGE.get("settings")).settings, + ); + if (parsedSettings.success) { + return parsedSettings.data; + } else { + return DEFAULT_SETTINGS; + } } export function subscribeToSettingsChanges( callback: (settings: Settings) => void, ) { - chrome.storage.sync.onChanged.addListener((changes) => { + STORAGE.onChanged.addListener((changes) => { if (changes.settings === undefined) { return; } - callback(changes.settings.newValue as Settings); + const parsedSettings = zSettingsSchema.safeParse(changes.settings.newValue); + if (parsedSettings.success) { + callback(parsedSettings.data); + } else { + callback(DEFAULT_SETTINGS); + } }); } |
