You need to sign in or sign up before continuing.
rebuild-tree.js 2.39 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
const _ = require('lodash')

/* global WIKI */

module.exports = async (pageId) => {
  WIKI.logger.info(`Rebuilding page tree...`)

  try {
    WIKI.models = require('../core/db').init()
    await WIKI.configSvc.loadFromDb()
    await WIKI.configSvc.applyFlags()

    const pages = await WIKI.models.pages.query().select('id', 'path', 'localeCode', 'title', 'isPrivate', 'privateNS').orderBy(['localeCode', 'path'])
    let tree = []
    let pik = 0

    for (const page of pages) {
      const pagePaths = page.path.split('/')
      let currentPath = ''
      let depth = 0
      let parentId = null
22
      let ancestors = []
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
      for (const part of pagePaths) {
        depth++
        const isFolder = (depth < pagePaths.length)
        currentPath = currentPath ? `${currentPath}/${part}` : part
        const found = _.find(tree, {
          localeCode: page.localeCode,
          path: currentPath
        })
        if (!found) {
          pik++
          tree.push({
            id: pik,
            localeCode: page.localeCode,
            path: currentPath,
            depth: depth,
            title: isFolder ? part : page.title,
            isFolder: isFolder,
            isPrivate: !isFolder && page.isPrivate,
            privateNS: !isFolder ? page.privateNS : null,
            parent: parentId,
43 44
            pageId: isFolder ? null : page.id,
            ancestors: JSON.stringify(ancestors)
45 46
          })
          parentId = pik
47 48 49
        } else if (isFolder && !found.isFolder) {
          found.isFolder = true
          parentId = found.id
50 51 52
        } else {
          parentId = found.id
        }
53
        ancestors.push(parentId)
54 55 56
      }
    }

57
    await WIKI.models.knex.table('pageTree').truncate()
58
    if (tree.length > 0) {
59
      // -> Save in chunks, because of per query max parameters (35k Postgres, 2k MSSQL, 1k for SQLite)
60
      if ((WIKI.config.db.type !== 'sqlite')) {
61 62 63 64 65 66 67
        for (const chunk of _.chunk(tree, 100)) {
          await WIKI.models.knex.table('pageTree').insert(chunk)
        }
      } else {
        for (const chunk of _.chunk(tree, 60)) {
          await WIKI.models.knex.table('pageTree').insert(chunk)
        }
68
      }
69 70 71 72 73 74 75 76
    }

    await WIKI.models.knex.destroy()

    WIKI.logger.info(`Rebuilding page tree: [ COMPLETED ]`)
  } catch (err) {
    WIKI.logger.error(`Rebuilding page tree: [ FAILED ]`)
    WIKI.logger.error(err.message)
77 78
    // exit process with error code
    throw err
79 80
  }
}