aboutsummaryrefslogtreecommitdiff
path: root/src/stores
diff options
context:
space:
mode:
Diffstat (limited to 'src/stores')
-rw-r--r--src/stores/identity.ts53
-rw-r--r--src/stores/userIdentity.ts10
2 files changed, 53 insertions, 10 deletions
diff --git a/src/stores/identity.ts b/src/stores/identity.ts
new file mode 100644
index 00000000..765ce5b2
--- /dev/null
+++ b/src/stores/identity.ts
@@ -0,0 +1,53 @@
+import { browser } from '$app/environment';
+import type { UserIdentity } from '$lib/AniList/identity';
+import { writable } from 'svelte/store';
+
+const defaultIdentity: UserIdentity = {
+ name: '',
+ id: -1,
+ avatar: 'https://s4.anilist.co/file/anilistcdn/user/avatar/large/default.png'
+};
+
+const createStore = () => {
+ const { subscribe, set, update } = writable<UserIdentity>(
+ JSON.parse(
+ browser
+ ? localStorage.getItem('identity') ?? JSON.stringify(defaultIdentity)
+ : JSON.stringify(defaultIdentity)
+ )
+ );
+ let state: UserIdentity;
+
+ subscribe((value) => (state = value));
+
+ return {
+ subscribe,
+ set,
+ update,
+ reset: () => set(defaultIdentity),
+ get: () => {
+ const keys = Object.keys(defaultIdentity);
+ const identityKeys = Object.keys(state);
+ const updatedIdentity = { ...state };
+
+ for (const key of keys)
+ if (!identityKeys.includes(key))
+ (updatedIdentity[key as keyof UserIdentity] as unknown) =
+ defaultIdentity[key as keyof UserIdentity];
+
+ if (browser) localStorage.setItem('identity', JSON.stringify(updatedIdentity));
+
+ return updatedIdentity;
+ },
+ setKey: (key: keyof UserIdentity, value: unknown) =>
+ update((identity) => ({ ...identity, [key]: value }))
+ };
+};
+
+const identity = createStore();
+
+identity.subscribe((value) => {
+ if (browser) localStorage.setItem('identity', JSON.stringify(value));
+});
+
+export default identity;
diff --git a/src/stores/userIdentity.ts b/src/stores/userIdentity.ts
deleted file mode 100644
index 4b90358d..00000000
--- a/src/stores/userIdentity.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { browser } from '$app/environment';
-import { writable } from 'svelte/store';
-
-const userIdentity = writable<string>(browser ? localStorage.getItem('userIdentity') ?? '' : '');
-
-userIdentity.subscribe((value) => {
- if (browser) localStorage.setItem('userIdentity', value);
-});
-
-export default userIdentity;