umami/store/version.js

56 lines
1.1 KiB
JavaScript
Raw Normal View History

import create from 'zustand';
import produce from 'immer';
import semver from 'semver';
import { VERSION_CHECK } from 'lib/constants';
import { getItem } from 'lib/web';
2022-06-24 10:54:55 +02:00
const UPDATES_URL = 'https://api.umami.is/v1/updates';
const initialState = {
2022-06-24 10:54:55 +02:00
current: process.env.currentVersion,
latest: null,
hasUpdate: false,
2022-06-24 10:54:55 +02:00
checked: false,
};
const store = create(() => ({ ...initialState }));
export async function checkVersion() {
const { current } = store.getState();
2022-06-24 10:54:55 +02:00
const data = await fetch(`${UPDATES_URL}?v=${current}`, {
method: 'GET',
headers: {
2022-06-03 16:06:44 +02:00
Accept: 'application/json',
},
}).then(res => {
if (res.ok) {
return res.json();
}
return null;
});
if (!data) {
return;
}
store.setState(
produce(state => {
2022-06-03 16:06:44 +02:00
const { latest } = data;
const lastCheck = getItem(VERSION_CHECK);
2022-06-24 10:54:55 +02:00
const hasUpdate = !!(latest && lastCheck?.version !== latest && semver.gt(latest, current));
state.current = current;
state.latest = latest;
state.hasUpdate = hasUpdate;
2022-06-24 10:54:55 +02:00
state.checked = true;
return state;
}),
);
}
export default store;