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.

80 lines
2.4 KiB

  1. const _ = require('lodash')
  2. /* global WIKI */
  3. module.exports = async (pageId) => {
  4. WIKI.logger.info(`Rebuilding page tree...`)
  5. try {
  6. WIKI.models = require('../core/db').init()
  7. await WIKI.configSvc.loadFromDb()
  8. await WIKI.configSvc.applyFlags()
  9. const pages = await WIKI.models.pages.query().select('id', 'path', 'localeCode', 'title', 'isPrivate', 'privateNS').orderBy(['localeCode', 'path'])
  10. let tree = []
  11. let pik = 0
  12. for (const page of pages) {
  13. const pagePaths = page.path.split('/')
  14. let currentPath = ''
  15. let depth = 0
  16. let parentId = null
  17. let ancestors = []
  18. for (const part of pagePaths) {
  19. depth++
  20. const isFolder = (depth < pagePaths.length)
  21. currentPath = currentPath ? `${currentPath}/${part}` : part
  22. const found = _.find(tree, {
  23. localeCode: page.localeCode,
  24. path: currentPath
  25. })
  26. if (!found) {
  27. pik++
  28. tree.push({
  29. id: pik,
  30. localeCode: page.localeCode,
  31. path: currentPath,
  32. depth: depth,
  33. title: isFolder ? part : page.title,
  34. isFolder: isFolder,
  35. isPrivate: !isFolder && page.isPrivate,
  36. privateNS: !isFolder ? page.privateNS : null,
  37. parent: parentId,
  38. pageId: isFolder ? null : page.id,
  39. ancestors: JSON.stringify(ancestors)
  40. })
  41. parentId = pik
  42. } else if (isFolder && !found.isFolder) {
  43. found.isFolder = true
  44. parentId = found.id
  45. } else {
  46. parentId = found.id
  47. }
  48. ancestors.push(parentId)
  49. }
  50. }
  51. await WIKI.models.knex.table('pageTree').truncate()
  52. if (tree.length > 0) {
  53. // -> Save in chunks, because of per query max parameters (35k Postgres, 2k MSSQL, 1k for SQLite)
  54. if ((WIKI.config.db.type !== 'sqlite')) {
  55. for (const chunk of _.chunk(tree, 100)) {
  56. await WIKI.models.knex.table('pageTree').insert(chunk)
  57. }
  58. } else {
  59. for (const chunk of _.chunk(tree, 60)) {
  60. await WIKI.models.knex.table('pageTree').insert(chunk)
  61. }
  62. }
  63. }
  64. await WIKI.models.knex.destroy()
  65. WIKI.logger.info(`Rebuilding page tree: [ COMPLETED ]`)
  66. } catch (err) {
  67. WIKI.logger.error(`Rebuilding page tree: [ FAILED ]`)
  68. WIKI.logger.error(err.message)
  69. // exit process with error code
  70. throw err
  71. }
  72. }