const mime = require('mime-types'); const path = require('path'); const fs = require('fs'); const CONFIG = require('./config.js'); function RouterUtils(app) { this.app = app; } RouterUtils.prototype.httpResponse = function(res, code, response) { res.writeHead(code); res.end(response); return true; } RouterUtils.prototype.redirect = function(res, url) { res.writeHead(302, { Location: url }); res.end(); } RouterUtils.prototype.apiError = function(res) { res.writeHead(400, { "Content-Type": "application/json"}); res.end(); } RouterUtils.prototype.jsonResponse = function(res, data) { res.writeHead(200, { "Content-Type": "application/json"}); if (typeof data !== 'string') data = JSON.stringify(data); res.end(data); } RouterUtils.prototype.onPageNotFound = function(res) { return this.httpResponse(res, 404, "Page not found..."); } RouterUtils.prototype.staticServe = async function(res, filePath) { return new Promise((ok, ko) => { const stream = fs.createReadStream(filePath); const fileSize = fs.statSync(filePath)?.size || undefined; if (!stream || !fileSize) { console.error("RouterUtils::staticGet", url, err); this.httpResponse(res, 500, "Internal Server Error"); return ko(err); } res.writeHead(200, { "Content-Type": mime.contentType(path.basename(filePath)), "Content-Length": fileSize }); stream.pipe(res); stream.once('end', () => ok()); }); } RouterUtils.prototype.staticGet = function(app, url, staticResources) { app.router.get(url, (req, res) => { app.routerUtils.staticServe(res, staticResources); }); } RouterUtils.prototype.commonRenderInfos = function(endpointName) { let context = { page_title: CONFIG.sitename, endpoints: [], currentEndpoint: endpointName }; for (let endpoint in CONFIG.endpoints) context.endpoints.push({ name: endpoint, address: '/dashboard/'+this.encodeUrlComponent(endpoint), selected: endpoint === endpointName, icon: CONFIG.endpoints[endpoint].icon }); return context; } module.exports = { RouterUtils: RouterUtils, encodeUrlComponent: RouterUtils.encodeUrlComponent, decodeUrlComponent: RouterUtils.decodeUrlComponent };