AutoReloader generalization

This commit is contained in:
Sebastian Seedorf
2020-11-18 23:38:53 +01:00
parent 18d4cc0ec0
commit ad653f6568
3 changed files with 105 additions and 51 deletions

View File

@@ -3,26 +3,54 @@ import {DefaultConfig, Logger, urlJoin} from '.';
import {v4} from 'uuid';
import Timeout = NodeJS.Timeout;
const router = Router();
if (!DefaultConfig.isProduction) {
let uuid = v4();
let updateTimeout: Timeout|undefined = undefined;
import("node-watch").then((watch) => {
watch.default('public', {recursive: true}, () => {
if (updateTimeout !== undefined) clearTimeout(updateTimeout);
updateTimeout = setTimeout(() => {
uuid = v4();
}, 200);
});
}).catch((err) => { Logger.error(err); });
export type ReloaderConfig = {
// frontend directories to watch
frontendDirs: string|string[],
// auto reloader sub path (defaults to '/auto-reload')
subPath?: string,
// auto reloader js name (defaults to 'client.js')
jsName?: string,
}
router.get("/auto-reload/client.js", (req, res) => {
Logger.debug(req.url, req.originalUrl, req.baseUrl);
res.setHeader('Content-Type', "application/javascript");
// language=JavaScript
res.send(`
type IntReloaderConfig = {
// frontend directories to watch
frontendDirs: string[],
// auto reloader sub path (defaults to '/auto-reload')
subPath: string,
// auto reloader js name (defaults to 'client.js')
jsName: string,
}
function getRouter(opts: ReloaderConfig): Router {
const config: IntReloaderConfig = {
frontendDirs: Array.isArray(opts.frontendDirs) ? opts.frontendDirs : [opts.frontendDirs],
subPath: opts.subPath || '/auto-reload',
jsName: opts.jsName || 'client.js',
};
const router = Router();
if (!DefaultConfig.isProduction) {
let uuid = v4();
let updateTimeout: Timeout|undefined = undefined;
import("node-watch").then((watch) => {
for (const frontendDir of config.frontendDirs) {
watch.default(frontendDir, {recursive: true}, () => {
if (updateTimeout !== undefined) clearTimeout(updateTimeout);
updateTimeout = setTimeout(() => {
uuid = v4();
}, 200);
});
}
}).catch((err) => { Logger.error(err); });
// /auto-reload/client.js
router.get(urlJoin(config.subPath, config.jsName), (req, res) => {
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+'${urlJoin(req.baseUrl, "/auto-reload")}';
const url = loc.protocol+'//'+loc.host+'${urlJoin(req.baseUrl, config.subPath)}';
// const parse = async res => (await res.json()).uuid;
const parse = function(res) {
return res.json()
@@ -49,14 +77,20 @@ if (!DefaultConfig.isProduction) {
}
}, 3000);
`.replace(/\t/g, ""));
});
});
router.get("/auto-reload", (req, res) => {
req.noHttpLogging = true;
res.json({uuid});
});
// /auto-reload
router.get(urlJoin(config.subPath), (req, res) => {
req.noHttpLogging = true;
res.json({uuid});
});
}
return router;
}
export const AutoReloader = {
router,
getRouter,
};