umami/redux/actions/app.js

77 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-09-07 10:22:16 +02:00
import { createSlice } from '@reduxjs/toolkit';
2020-09-30 06:22:08 +02:00
import { getItem } from 'lib/web';
import { LOCALE_CONFIG, THEME_CONFIG, VERSION_CHECK } from 'lib/constants';
import semver from 'semver';
2020-09-07 10:22:16 +02:00
const app = createSlice({
name: 'app',
2020-09-20 10:33:39 +02:00
initialState: {
locale: getItem(LOCALE_CONFIG) || 'en-US',
theme: getItem(THEME_CONFIG) || 'light',
versions: {
current: process.env.VERSION,
latest: null,
hasUpdate: false,
},
2020-09-20 10:33:39 +02:00
},
2020-09-07 10:22:16 +02:00
reducers: {
2020-09-20 10:33:39 +02:00
setLocale(state, action) {
state.locale = action.payload;
return state;
},
setTheme(state, action) {
state.theme = action.payload;
2020-09-07 10:22:16 +02:00
return state;
},
setVersions(state, action) {
state.versions = action.payload;
return state;
},
2020-09-07 10:22:16 +02:00
},
});
export const { setLocale, setTheme, setVersions } = app.actions;
2020-09-07 10:22:16 +02:00
export default app.reducer;
export function checkVersion() {
return async (dispatch, getState) => {
const {
app: {
versions: { current },
},
} = getState();
2020-09-30 06:22:08 +02:00
const data = await fetch('https://api.github.com/repos/mikecao/umami/releases/latest', {
method: 'get',
headers: {
Accept: 'application/vnd.github.v3+json',
},
}).then(res => {
if (res.ok) {
return res.json();
}
2020-09-30 06:22:08 +02:00
return null;
});
2020-09-30 06:22:08 +02:00
if (!data) {
return;
}
2020-09-30 06:22:08 +02:00
const { tag_name } = data;
2020-09-30 06:22:08 +02:00
const latest = tag_name.startsWith('v') ? tag_name.slice(1) : tag_name;
const lastCheck = getItem(VERSION_CHECK);
const hasUpdate = latest && semver.gt(latest, current) && lastCheck?.version !== latest;
2020-09-30 06:22:08 +02:00
return dispatch(
setVersions({
current,
latest,
hasUpdate,
2020-09-30 06:22:08 +02:00
}),
);
};
}