aboutsummaryrefslogtreecommitdiff
path: root/src/stores/lastPruneTimes.ts
blob: 212f2bc93b4e446bf0a7e2c6f523ad83121b1128 (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
55
56
import { browser } from '$app/environment';
import { writable } from 'svelte/store';
import localforage from 'localforage';

interface LastPruneTimes {
  anime: number;
  chapters: number;
  manga: number;
}

const defaultTimes: LastPruneTimes = {
  anime: 1,
  chapters: 1,
  manga: 1
};

const createStore = () => {
  const store = writable<LastPruneTimes>(defaultTimes);
  let state: LastPruneTimes = defaultTimes;

  if (browser)
    localforage.getItem<LastPruneTimes>('lastPruneTimes').then((value) => {
      if (value && Object.keys(value).length === Object.keys(defaultTimes).length) store.set(value);
    });

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

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

  return {
    subscribe: store.subscribe,
    set: store.set,
    update: store.update,
    reset: () => store.set(defaultTimes),

    get: () => {
      const keys = Object.keys(defaultTimes);
      const stateKeys = Object.keys(state);

      if (keys.length !== stateKeys.length) return defaultTimes;

      for (const key of keys) if (!stateKeys.includes(key)) return defaultTimes;

      return state;
    },

    setKey: (key: keyof LastPruneTimes, value: number) =>
      store.update((times) => ({ ...times, [key]: value }))
  };
};

const lastPruneTimes = createStore();

export default lastPruneTimes;