aboutsummaryrefslogtreecommitdiff
path: root/src/store/version.ts
blob: 95367afd742af035eb898976ac5a66a719a46951 (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
import { produce } from 'immer';
import semver from 'semver';
import { create } from 'zustand';
import { CURRENT_VERSION, UPDATES_URL, VERSION_CHECK } from '@/lib/constants';
import { getItem } from '@/lib/storage';

const initialState = {
  current: CURRENT_VERSION,
  latest: null,
  hasUpdate: false,
  checked: false,
  releaseUrl: null,
};

const store = create(() => ({ ...initialState }));

export async function checkVersion() {
  const { current } = store.getState();

  const data = await fetch(`${UPDATES_URL}?v=${current}`, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
  }).then(res => {
    if (res.ok) {
      return res.json();
    }

    return null;
  });

  if (!data) {
    return;
  }

  store.setState(
    produce(state => {
      const { latest, url } = data;
      const lastCheck = getItem(VERSION_CHECK);

      const hasUpdate = !!(latest && lastCheck?.version !== latest && semver.gt(latest, current));

      state.current = current;
      state.latest = latest;
      state.hasUpdate = hasUpdate;
      state.checked = true;
      state.releaseUrl = url;

      return state;
    }),
  );
}

export const useVersion = store;