routerUtils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const mime = require('mime-types');
  2. const path = require('path');
  3. const fs = require('fs');
  4. const CONFIG = require('./config.js');
  5. function RouterUtils(app) {
  6. this.app = app;
  7. }
  8. RouterUtils.prototype.httpResponse = function(res, code, response) {
  9. res.writeHead(code);
  10. res.end(response);
  11. return true;
  12. }
  13. RouterUtils.prototype.redirect = function(res, url) {
  14. res.writeHead(302, { Location: url });
  15. res.end();
  16. }
  17. RouterUtils.prototype.apiError = function(res) {
  18. res.writeHead(400, { "Content-Type": "application/json"});
  19. res.end();
  20. }
  21. RouterUtils.prototype.jsonResponse = function(res, data) {
  22. res.writeHead(200, { "Content-Type": "application/json"});
  23. if (typeof data !== 'string')
  24. data = JSON.stringify(data);
  25. res.end(data);
  26. }
  27. RouterUtils.prototype.onPageNotFound = function(res) {
  28. return this.httpResponse(res, 404, "Page not found...");
  29. }
  30. RouterUtils.prototype.staticServe = async function(res, filePath) {
  31. return new Promise((ok, ko) => {
  32. const stream = fs.createReadStream(filePath);
  33. const fileSize = fs.statSync(filePath)?.size || undefined;
  34. if (!stream || !fileSize) {
  35. console.error("RouterUtils::staticGet", url, err);
  36. this.httpResponse(res, 500, "Internal Server Error");
  37. return ko(err);
  38. }
  39. res.writeHead(200, {
  40. "Content-Type": mime.contentType(path.basename(filePath)),
  41. "Content-Length": fileSize
  42. });
  43. stream.pipe(res);
  44. stream.once('end', () => ok());
  45. });
  46. }
  47. RouterUtils.prototype.staticGet = function(app, url, staticResources) {
  48. app.router.get(url, (req, res) => {
  49. app.routerUtils.staticServe(res, staticResources);
  50. });
  51. }
  52. RouterUtils.prototype.commonRenderInfos = function(endpointName) {
  53. let context = {
  54. page_title: CONFIG.sitename,
  55. endpoints: [],
  56. currentEndpoint: endpointName
  57. };
  58. for (let endpoint in CONFIG.endpoints)
  59. context.endpoints.push({
  60. name: endpoint,
  61. address: '/dashboard/'+this.encodeUrlComponent(endpoint),
  62. selected: endpoint === endpointName,
  63. icon: CONFIG.endpoints[endpoint].icon
  64. });
  65. return context;
  66. }
  67. module.exports = { RouterUtils: RouterUtils, encodeUrlComponent: RouterUtils.encodeUrlComponent, decodeUrlComponent: RouterUtils.decodeUrlComponent };