render-page.js 2.58 KB
Newer Older
1
const _ = require('lodash')
2
const cheerio = require('cheerio')
3

4 5
/* global WIKI */

6 7
module.exports = async (pageId) => {
  WIKI.logger.info(`Rendering page ID ${pageId}...`)
8 9

  try {
10
    WIKI.models = require('../core/db').init()
Nick's avatar
Nick committed
11 12
    await WIKI.configSvc.loadFromDb()
    await WIKI.configSvc.applyFlags()
13 14 15 16 17 18 19 20 21 22

    const page = await WIKI.models.pages.getPageFromDb(pageId)
    if (!page) {
      throw new Error('Invalid Page Id')
    }

    await WIKI.models.renderers.fetchDefinitions()
    const pipeline = await WIKI.models.renderers.getRenderingPipeline(page.contentType)

    let output = page.content
23 24 25 26 27 28

    if (_.isEmpty(page.content)) {
      await WIKI.models.knex.destroy()
      WIKI.logger.warn(`Failed to render page ID ${pageId} because content was empty: [ FAILED ]`)
    }

29
    for (let core of pipeline) {
30 31 32 33
      const renderer = require(`../modules/rendering/${_.kebabCase(core.key)}/renderer.js`)
      output = await renderer.render.call({
        config: core.config,
        children: core.children,
34
        page: page,
35 36 37
        input: output
      })
    }
38

39 40 41 42 43 44 45
    // Parse TOC
    const $ = cheerio.load(output)
    let isStrict = $('h1').length > 0 // <- Allows for documents using H2 as top level
    let toc = { root: [] }

    $('h1,h2,h3,h4,h5,h6').each((idx, el) => {
      const depth = _.toSafeInteger(el.name.substring(1)) - (isStrict ? 1 : 2)
46 47
      let leafPathError = false

48 49 50
      const leafPath = _.reduce(_.times(depth), (curPath, curIdx) => {
        if (_.has(toc, curPath)) {
          const lastLeafIdx = _.get(toc, curPath).length - 1
51 52 53 54 55
          if (lastLeafIdx >= 0) {
            curPath = `${curPath}[${lastLeafIdx}].children`
          } else {
            leafPathError = true
          }
56 57 58 59
        }
        return curPath
      }, 'root')

60 61
      if (leafPathError) { return }

62 63
      const leafSlug = $('.toc-anchor', el).first().attr('href')
      $('.toc-anchor', el).remove()
64

65 66 67 68 69 70 71
      _.get(toc, leafPath).push({
        title: _.trim($(el).text()),
        anchor: leafSlug,
        children: []
      })
    })

72 73
    // Save to DB
    await WIKI.models.pages.query()
74 75 76 77
      .patch({
        render: output,
        toc: JSON.stringify(toc.root)
      })
78
      .where('id', pageId)
79 80 81

    // Save to cache
    await WIKI.models.pages.savePageToCache({
82
      ...page,
83 84
      render: output,
      toc: JSON.stringify(toc.root)
85
    })
86

87 88 89
    await WIKI.models.knex.destroy()

    WIKI.logger.info(`Rendering page ID ${pageId}: [ COMPLETED ]`)
90
  } catch (err) {
91
    WIKI.logger.error(`Rendering page ID ${pageId}: [ FAILED ]`)
92
    WIKI.logger.error(err.message)
93 94
    // exit process with error code
    throw err
95 96
  }
}