Skip to content

Commit

Permalink
feat: add DeployReload class to check whether system needs to be updated
Browse files Browse the repository at this point in the history
  • Loading branch information
flingyp committed Jan 15, 2024
1 parent 1a84a86 commit eeeb614
Show file tree
Hide file tree
Showing 10 changed files with 146 additions and 8 deletions.
2 changes: 2 additions & 0 deletions auto-imports.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// Generated by unplugin-auto-import
export {}
declare global {
const DeployReload: typeof import('./src/utils/reload')['DeployReload']
const EffectScope: typeof import('vue')['EffectScope']
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
const addThemeCssVariousToHtml: typeof import('./src/utils/colord')['addThemeCssVariousToHtml']
Expand Down Expand Up @@ -325,6 +326,7 @@ declare global {
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface ComponentCustomProperties {
readonly DeployReload: UnwrapRef<typeof import('./src/utils/reload')['DeployReload']>
readonly EffectScope: UnwrapRef<typeof import('vue')['EffectScope']>
readonly acceptHMRUpdate: UnwrapRef<typeof import('pinia')['acceptHMRUpdate']>
readonly addThemeCssVariousToHtml: UnwrapRef<typeof import('./src/utils/colord')['addThemeCssVariousToHtml']>
Expand Down
23 changes: 21 additions & 2 deletions build/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { Plugin as viteCDNPlugin } from 'vite-plugin-cdn-import';
import { VitePWA } from 'vite-plugin-pwa';
import VueDevTools from 'vite-plugin-vue-devtools';

import { useGetCurrentPath } from '@flypeng/tool/node';
import { writeFileSync } from 'fs';

import { name, version } from '../package.json';

/**
Expand All @@ -20,8 +23,8 @@ import { name, version } from '../package.json';
* @param mode
* @returns
*/
export const generatePlugins = (command: string, mode: string): PluginOption[] => {
const pluginList = [
export const generatePlugins = (command: string, mode: string, buildTimestamp: number): PluginOption[] => {
const pluginList: PluginOption[] = [
vue(),
// Mock Api
ViteMockServe({
Expand Down Expand Up @@ -88,6 +91,7 @@ export const generatePlugins = (command: string, mode: string): PluginOption[] =
],
},
}),
// Packages CDN Links
viteCDNPlugin({
modules: [
{
Expand Down Expand Up @@ -178,6 +182,21 @@ export const generatePlugins = (command: string, mode: string): PluginOption[] =
],
},
}),

// Build End Plugin
{
name: 'vite-plugin-vadmire-buildEnding',
buildStart: () => {
console.log('构建开始', buildTimestamp, useGetCurrentPath());
writeFileSync(
`${useGetCurrentPath()}/public/config.json`,
`{
"buildTime": ${buildTimestamp}
}`,
{ encoding: 'utf-8' },
);
},
},
];

if (mode === 'development') {
Expand Down
10 changes: 5 additions & 5 deletions components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ declare module '@vue/runtime-core' {
NCard: typeof import('naive-ui')['NCard']
NColorPicker: typeof import('naive-ui')['NColorPicker']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDataTable: (typeof import('naive-ui'))['NDataTable']
NDatePicker: (typeof import('naive-ui'))['NDatePicker']
NDataTable: typeof import('naive-ui')['NDataTable']
NDatePicker: typeof import('naive-ui')['NDatePicker']
NDescriptions: typeof import('naive-ui')['NDescriptions']
NDescriptionsItem: typeof import('naive-ui')['NDescriptionsItem']
NDialogProvider: typeof import('naive-ui')['NDialogProvider']
Expand All @@ -63,7 +63,7 @@ declare module '@vue/runtime-core' {
NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem']
NInput: typeof import('naive-ui')['NInput']
NInputGroup: (typeof import('naive-ui'))['NInputGroup']
NInputGroup: typeof import('naive-ui')['NInputGroup']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutContent: typeof import('naive-ui')['NLayoutContent']
Expand All @@ -73,11 +73,11 @@ declare module '@vue/runtime-core' {
NMenu: typeof import('naive-ui')['NMenu']
NMessageProvider: typeof import('naive-ui')['NMessageProvider']
NNotificationProvider: typeof import('naive-ui')['NNotificationProvider']
NPopover: (typeof import('naive-ui'))['NPopover']
NPopover: typeof import('naive-ui')['NPopover']
NSelect: typeof import('naive-ui')['NSelect']
NSpin: typeof import('naive-ui')['NSpin']
NSwitch: typeof import('naive-ui')['NSwitch']
NTag: (typeof import('naive-ui'))['NTag']
NTag: typeof import('naive-ui')['NTag']
RenderIconify: typeof import('./src/components/common/RenderIconify.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
Expand Down
3 changes: 3 additions & 0 deletions public/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"buildTime": 17053021998210
}
36 changes: 36 additions & 0 deletions src/RouterContent.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
<script setup lang="ts">
import { useDialog } from 'naive-ui';
import { DeployReload } from '~/utils';
const isOnline = useOnline();
const { success, error } = useNaiveNotification();
watch(
() => isOnline.value,
(newVal, oldVal) => {
Expand All @@ -12,6 +16,38 @@ watch(
}
},
);
// listening system whether updated
const dialog = useDialog();
const isOpenDialog = ref(true);
new DeployReload({
fetchUrl: 'http://localhost:8080/config.json',
fetchKey: 'buildTime',
checkTimeout: 60 * 5,
execute: true,
reloadCallback() {
if (isOpenDialog.value) {
isOpenDialog.value = false;
dialog.warning({
title: '提示',
content: '检测到系统已更新最新版本,请重新加载页面',
positiveText: '更新',
negativeText: '不更新',
closable: false,
closeOnEsc: false,
maskClosable: false,
onPositiveClick: () => {
isOpenDialog.value = true;
location.reload();
},
onNegativeClick: () => {
isOpenDialog.value = true;
},
});
}
},
});
</script>

<template>
Expand Down
1 change: 1 addition & 0 deletions src/components/common/SingleApp.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { darkTheme, zhCN, dateZhCN, enUS, dateEnUS, koKR, dateKoKR } from 'naive-ui';
import { useVAdmireConfigStore } from '~/store';
import BaseSpin from '~/components/common/BaseSpin.vue';
defineOptions({ name: 'SingleApp' });
Expand Down
1 change: 1 addition & 0 deletions src/composables/common/useApp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { THEME_MODE_KEY } from '~/vadmire.config';
// To do things when init application
export function useApp() {
const { t } = useI18n();

const route = useRoute();
const { toggleDark } = useTheme();
const vadmireConfigStore = useVAdmireConfigStore();
Expand Down
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './colord';
export * from './echarts';
export * from './i18n';
export * from './dayjs';
export * from './reload';
75 changes: 75 additions & 0 deletions src/utils/reload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* fetchUrl: 请求的地址
* fetchKey: 获取的字段
* checkTimeout: 多久检查一次
* execute: 是否立即执行
* reloadCallback: 更新执行回调
*/
interface DeployReloadOptions {
fetchUrl: string;
fetchKey: string;
checkTimeout?: number;
execute?: boolean;
reloadCallback?: () => void;
}

export class DeployReload {
private fetchUrl: string;
private fetchKey: string;
private stashBuildTime: number = 0;
private checkTimeout: number; // Second
private execute: boolean = false;
private intervalInstance: any;

private reloadCallback: () => void;

constructor(options: DeployReloadOptions) {
this.fetchUrl = options.fetchUrl;
this.fetchKey = options.fetchKey;
this.checkTimeout = options.checkTimeout || 5;
this.execute = options.execute || false;

this.reloadCallback = options.reloadCallback || (() => {});

this.init();
}

private init() {
this.getBuildTimeValue().then((value) => {
this.stashBuildTime = value;
});

const timeoutValue = this.checkTimeout * 1000;
const callback = this.checkBuildTime.bind(this);
this.execute && callback();
this.intervalInstance = setInterval(callback, timeoutValue);

document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
console.log('22222');
this.execute && callback();

this.intervalInstance = setInterval(callback, timeoutValue);
} else {
clearInterval(this.intervalInstance);
}
});
}

private async getBuildTimeValue() {
const response = await fetch(`${this.fetchUrl}?time=${new Date().getTime()}`);
const result = (await response.json()) as Record<string, any>;
return result[this.fetchKey] as number;
}

private async checkBuildTime() {
const currentBuildTime = await this.getBuildTimeValue();
if (currentBuildTime > this.stashBuildTime) {
this.reload();
}
}

private reload() {
this.reloadCallback();
}
}
2 changes: 1 addition & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default ({ mode, command }: ConfigEnv): UserConfigExport => ({
},
},
// Plugins config
plugins: generatePlugins(command, mode),
plugins: generatePlugins(command, mode, currentTimestamp),
// Build config
build: {
rollupOptions: {
Expand Down

0 comments on commit eeeb614

Please sign in to comment.