aboutsummaryrefslogtreecommitdiff
path: root/src/stores/identity.ts
blob: 596c7176f79ac1140e6d8cff9e7a66b9ad1da9e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { browser } from '$app/environment';
import type { UserIdentity } from '$lib/Data/AniList/identity';
import { writable } from 'svelte/store';
import localforage from 'localforage';

export const defaultIdentity: UserIdentity = {
  name: '',
  id: -2,
  avatar: 'https://s4.anilist.co/file/anilistcdn/user/avatar/large/default.png'
};

const createStore = () => {
  const store = writable<UserIdentity>(defaultIdentity);
  let state: UserIdentity = defaultIdentity;

  if (browser)
    localforage.getItem<UserIdentity>('identity').then((value) => {
      if (value && typeof value === 'object') store.set(value);
    });

  store.subscribe((value) => {
    state = value;

    if (browser) localforage.setItem('identity', value);
  });

  return {
    subscribe: store.subscribe,
    set: store.set,
    update: store.update,
    reset: () => store.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] = defaultIdentity[key as keyof UserIdentity];

      if (browser) localforage.setItem('identity', updatedIdentity);

      return updatedIdentity;
    },

    setKey: (key: keyof UserIdentity, value: unknown) =>
      store.update((identity) => ({ ...identity, [key]: value }))
  };
};

const identity = createStore();

export default identity;