aboutsummaryrefslogtreecommitdiff
path: root/src/stores/lastPruneTimes.ts
blob: 4741201eca2f0cf4cb623db08cf915405ea0868b (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
57
58
59
60
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;