A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
fix(extension): Fix handling for empty storage. #10
MohamedBassem7bffa02cf67b
diff --git a/apps/browser-extension/src/utils/settings.ts b/apps/browser-extension/src/utils/settings.tsindex 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);+ }});}