SPA 사이트는 특성상 배포를 할때마다 새로고침을 해야만 유저가 새 리소스를 다운받아 배포된 코드를 접할 수 있다. 그런데 새로고침을 해달라고 그때마다 말하는게 귀찮아서 web socket을 이용해 실시간으로 알림을 보내보자!
// ./server.js
/*
* Initialise Express
*/
const express = require('express');
var cors = require('cors');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname)));
app.use(cors());
/*
* Initialise Pusher
*/
const Pusher = require('pusher');
const pusher = new Pusher({
appId: '',
key: '',
secret: '',
cluster: '',
useTLS: true,
});
/*
* Define post route for creating new reviews
*/
app.post('/release-alarm', (req, res) => {
pusher.trigger('my-channel', 'my-event', req.body);
res.status(200).send();
});
/*
* Run app
*/
const port = 3001;
app.listen(port, () => {
console.log(`App listening on port ${port}!`);
});
// ./App.vue
<script setup>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('', {
cluster: '',
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function (data) {
pusherRefresh.value = data.alarm;
});
const clickResetConfirm = () => {
// 강력 새로고침
window.location.href = `${window.location.origin}${window.location.pathname}?refresh=` + new Date().getTime();
};
</script>
<template>
<el-dialog
v-model="pusherRefresh"
title="새로고침 하기"
width="30%"
:before-close="handleClose"
:close-on-press-escape="false"
:close-on-click-modal="false"
>
<div style="font-size: 16px; padding-bottom: 16px">주요 기능이 배포되어 <b>새로고침</b>이 필요합니다. <b>새로고침 버튼</b>을 눌러주세요.</div>
<div>
진행중인 작업이 있으실 경우 닫기 버튼을 누른 후 하던 작업을 마무리 하고, 반드시 <b>'Ctrl + Shift + R'</b>를 눌러 강력 새로고침 해주세요.
</div>
<template #footer>
<span class="dialog-footer">
<el-button type="primary" @click="clickResetConfirm"> 새로고침 </el-button>
</span>
</template>
</el-dialog>
</template>
<script setup>
import pureAxios from 'axios';
const clickBtn = async () => {
await pureAxios.post(
'/release-alarm',
{ alarm: true },
{ 'Content-Type': 'application/json' },
);
};
</script>
<template>
<el-button type="default" size="large" @click="clickBtn">배포 알람</el-button>
</template>