diff options
Diffstat (limited to 'src/stores/identity.ts')
| -rw-r--r-- | src/stores/identity.ts | 53 |
1 files changed, 53 insertions, 0 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; |