You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.3 KiB

  1. const _ = require('lodash')
  2. const cheerio = require('cheerio')
  3. /* global WIKI */
  4. module.exports = async (pageId) => {
  5. WIKI.logger.info(`Rendering page ID ${pageId}...`)
  6. try {
  7. WIKI.models = require('../core/db').init()
  8. const page = await WIKI.models.pages.getPageFromDb(pageId)
  9. if (!page) {
  10. throw new Error('Invalid Page Id')
  11. }
  12. await WIKI.models.renderers.fetchDefinitions()
  13. const pipeline = await WIKI.models.renderers.getRenderingPipeline(page.contentType)
  14. let output = page.content
  15. for (let core of pipeline) {
  16. const renderer = require(`../modules/rendering/${_.kebabCase(core.key)}/renderer.js`)
  17. output = await renderer.render.call({
  18. config: core.config,
  19. children: core.children,
  20. page: page,
  21. input: output
  22. })
  23. }
  24. // Parse TOC
  25. const $ = cheerio.load(output)
  26. let isStrict = $('h1').length > 0 // <- Allows for documents using H2 as top level
  27. let toc = { root: [] }
  28. $('h1,h2,h3,h4,h5,h6').each((idx, el) => {
  29. const depth = _.toSafeInteger(el.name.substring(1)) - (isStrict ? 1 : 2)
  30. let leafPathError = false
  31. const leafPath = _.reduce(_.times(depth), (curPath, curIdx) => {
  32. if (_.has(toc, curPath)) {
  33. const lastLeafIdx = _.get(toc, curPath).length - 1
  34. if (lastLeafIdx >= 0) {
  35. curPath = `${curPath}[${lastLeafIdx}].children`
  36. } else {
  37. leafPathError = true
  38. }
  39. }
  40. return curPath
  41. }, 'root')
  42. if (leafPathError) { return }
  43. const leafSlug = $('.toc-anchor', el).first().attr('href')
  44. $('.toc-anchor', el).remove()
  45. _.get(toc, leafPath).push({
  46. title: _.trim($(el).text()),
  47. anchor: leafSlug,
  48. children: []
  49. })
  50. })
  51. // Save to DB
  52. await WIKI.models.pages.query()
  53. .patch({
  54. render: output,
  55. toc: JSON.stringify(toc.root)
  56. })
  57. .where('id', pageId)
  58. // Save to cache
  59. await WIKI.models.pages.savePageToCache({
  60. ...page,
  61. render: output,
  62. toc: JSON.stringify(toc.root)
  63. })
  64. await WIKI.models.knex.destroy()
  65. WIKI.logger.info(`Rendering page ID ${pageId}: [ COMPLETED ]`)
  66. } catch (err) {
  67. WIKI.logger.error(`Rendering page ID ${pageId}: [ FAILED ]`)
  68. WIKI.logger.error(err.message)
  69. }
  70. }