Files
node-pkg-express-utils/out/auto-reload.js
Sebastian Seedorf 7ad9cd1904 inital #4
2020-11-16 12:44:08 +01:00

62 lines
1.9 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoReloader = void 0;
const express_1 = require("express");
const _1 = require(".");
const uuid_1 = require("uuid");
const router = express_1.Router();
if (!_1.DefaultConfig.isProduction) {
let uuid = uuid_1.v4();
let updateTimeout = undefined;
Promise.resolve().then(() => require("node-watch")).then((watch) => {
watch.default('public', { recursive: true }, () => {
if (updateTimeout !== undefined)
clearTimeout(updateTimeout);
updateTimeout = setTimeout(() => {
uuid = uuid_1.v4();
}, 200);
});
}).catch((err) => { _1.Logger.error(err); });
router.get("/auto-reload/client.js", (req, res) => {
_1.Logger.debug(req.url, req.originalUrl, req.baseUrl);
res.setHeader('Content-Type', "application/javascript");
// language=JavaScript
res.send(`
const loc = window.location;
const url = loc.protocol+'//'+loc.host+'${_1.urlJoin(req.baseUrl, "/auto-reload")}';
// const parse = async res => (await res.json()).uuid;
const parse = function(res) {
return res.json()
.then(function(json) {return json.uuid;}) }
let hash = undefined;
let hadError = false;
setInterval(function() {
try {
fetch(url)
.then(function(res) { return parse(res) })
.then(function(data) {
if (data) {
hash = hash === undefined ? data : hash;
if (hash !== data) {
window.location.reload();
}
}
});
} catch (e) {
if (hadError === false) {
console.log(e);
hadError = true;
}
}
}, 3000);
`.replace(/\t/g, ""));
});
router.get("/auto-reload", (req, res) => {
req.noLogging = true;
res.json({ uuid });
});
}
exports.AutoReloader = {
router,
};