indexHandlers.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /* global __dirname */
  2. "use strict";
  3. var _ = require('lodash');
  4. var Mustache = require('mustache');
  5. var path = require('path');
  6. var fs = require('fs');
  7. var chokidar = require('chokidar');
  8. var indexTmplPath = path.normalize(__dirname + '/../html/index.mustache.html');
  9. var indexTpml;
  10. var {
  11. readFilesAsync
  12. } = require('../lib/fsio');
  13. var translator = require('../lib/translator');
  14. var passLog = require('../lib/passLog');
  15. // One-liner for current directory, ignores .dotfiles
  16. chokidar.watch('./html', {ignored: /(^|[\/\\])\../}).on('all', (event, path) => {
  17. // console.log(event, path);
  18. if(path === 'html/index.mustache.html') {
  19. console.log('reload index html');
  20. indexTpml = fs.readFileSync(indexTmplPath).toString();
  21. }
  22. });
  23. module.exports = function(exStore, exDir, testMode) {
  24. function readExampleFiles(repoSlug, exampleSlug, config) {
  25. const exampleDir = exDir + '/' + repoSlug + '/' + exampleSlug;
  26. const libsCssDir = path.normalize(__dirname + '/../css/vendor');
  27. const libsJsDir = path.normalize(__dirname + '/../js/vendor');
  28. const { html, js, css } = config; // libsCss, libsJs
  29. const files = [].concat(html, js, css);
  30. return readFilesAsync(exampleDir, files);
  31. }
  32. function renderIndex(req, withRepo, withExample) {
  33. // Extract repoSlug and exampleSlug from req.params
  34. const { locale, params: { repoSlug, exampleSlug } } = req;
  35. let repo;
  36. let menuExample;
  37. let statusCode;
  38. const menuRepo = exStore.getRepoMenu();
  39. const translations = translator.getAll(locale);
  40. // Initialize view data
  41. let data = {
  42. menuRepo,
  43. reposJSON: JSON.stringify(menuRepo),
  44. repoJSON: 'null',
  45. exampleJSON: 'null',
  46. testMode,
  47. testRun: testMode && req.query.testing,
  48. appPath: req.path,
  49. _: translations,
  50. _JSON: JSON.stringify(translations)
  51. };
  52. // Fetch example repository if needed
  53. if(withRepo) {
  54. data.repo = exStore.getRepo(repoSlug);
  55. data.repoJSON = JSON.stringify(data.repo);
  56. if(! data.repo) {
  57. // return res.status(404).send('Repo ' + req.params.repoSlug + ' not found');
  58. data.errorMessage = translator.getOne(locale, "repoNotFound", [repoSlug]); //'Repo ' + params.repoSlug + ' not found';
  59. statusCode = 404;
  60. }
  61. else {
  62. data.menuExample = exStore.getExampleMenu(data.repo.path);
  63. data.showControls = true;
  64. }
  65. }
  66. // Fetch example if needed
  67. if(withExample && data.repo) {
  68. data.example = _.find(data.repo.examples, { slug: exampleSlug });
  69. data.exampleJSON = JSON.stringify(data.example);
  70. if(! data.example) {
  71. // return res.status(404).send('Example ' + req.params.repoSlug + '/' + req.params.exampleSlug + ' not found');
  72. data.errorMessage = translator.getOne(locale, "exampleNotFound", [repoSlug, exampleSlug]);
  73. statusCode = 404;
  74. }
  75. else {
  76. data.showEditor = true;
  77. }
  78. }
  79. data.showShortcutExample = data.repo && ! data.example;
  80. // Mustache.render(indexTpml, data);
  81. return (
  82. exampleSlug && data.example ?
  83. readExampleFiles(repoSlug, exampleSlug, data.example) : Promise.resolve([])
  84. ).then(files =>
  85. ({ files, filesJSON: JSON.stringify(files) })
  86. )
  87. .then(({ files, filesJSON }) => Object.assign(data, { files, filesJSON }))
  88. .then(passLog('data before rendering, path: ' + req.path))
  89. .then(data => ({
  90. html: Mustache.render(indexTpml, data),
  91. code: statusCode ? statusCode : 200
  92. }))
  93. .catch(err => {
  94. console.error(err);
  95. res.status(500).json({ error: err.message });
  96. });
  97. }
  98. return {
  99. /**
  100. * Extract language header from req
  101. */
  102. getAcceptLanguage: function (req, res, next) {
  103. const acceptLanguageHdr = req.headers["accept-language"];
  104. const re = /[a-z]{2}\-[A-Z]{2}/;
  105. const matches = re.exec(acceptLanguageHdr);
  106. if(matches) {
  107. req.locale = matches[0];
  108. }
  109. next();
  110. },
  111. /**
  112. * Get bare index without repo or examples
  113. */
  114. getIndexBare: function(req, res) {
  115. renderIndex(req)
  116. .then(({ html, code }) => res.send(html));
  117. },
  118. /**
  119. * Get index with repo selected only
  120. */
  121. getIndexRepo: function(req, res) {
  122. renderIndex(req, true)
  123. .then(({ html, code }) => res.status(code).send(html));
  124. },
  125. /**
  126. * Get index with selected repo&example
  127. */
  128. getIndexExample: function(req, res) {
  129. renderIndex(req, true, true)
  130. .then(({ html, code }) => res.status(code).send(html));
  131. }
  132. };
  133. };