render-page.js 2.4 KB

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