aboutsummaryrefslogtreecommitdiff
path: root/src/stores/lastPruneTimes.ts
blob: 2a77053824462dd3ae45925c845f930d58b35549 (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
61
62
63
64
65
66
67
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;
	let hydrated = !browser;

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

		if (browser && hydrated) localforage.setItem("lastPruneTimes", value);
	});

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

				hydrated = true;

				await localforage.setItem("lastPruneTimes", state);
			});

	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;