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.

67 lines
2.0 KiB

  1. const Model = require('objection').Model
  2. const _ = require('lodash')
  3. /* global WIKI */
  4. /**
  5. * Navigation model
  6. */
  7. module.exports = class Navigation extends Model {
  8. static get tableName() { return 'navigation' }
  9. static get idColumn() { return 'key' }
  10. static get jsonSchema () {
  11. return {
  12. type: 'object',
  13. required: ['key'],
  14. properties: {
  15. key: {type: 'string'},
  16. config: {type: 'array', items: {type: 'object'}}
  17. }
  18. }
  19. }
  20. static async getTree({ cache = false, locale = 'en', groups = [], bypassAuth = false } = {}) {
  21. if (cache) {
  22. const navTreeCached = await WIKI.cache.get(`nav:sidebar:${locale}`)
  23. if (navTreeCached) {
  24. return bypassAuth ? navTreeCached : WIKI.models.navigation.getAuthorizedItems(navTreeCached, groups)
  25. }
  26. }
  27. const navTree = await WIKI.models.navigation.query().findOne('key', `site`)
  28. if (navTree) {
  29. // Check for pre-2.3 format
  30. if (_.has(navTree.config[0], 'kind')) {
  31. navTree.config = [{
  32. locale: 'en',
  33. items: navTree.config.map(item => ({
  34. ...item,
  35. visibilityMode: 'all',
  36. visibilityGroups: []
  37. }))
  38. }]
  39. }
  40. for (const tree of navTree.config) {
  41. if (cache) {
  42. await WIKI.cache.set(`nav:sidebar:${tree.locale}`, tree.items, 300)
  43. }
  44. }
  45. if (bypassAuth) {
  46. return locale === 'all' ? navTree.config : WIKI.cache.get(`nav:sidebar:${locale}`)
  47. } else {
  48. return locale === 'all' ? WIKI.models.navigation.getAuthorizedItems(navTree.config, groups) : WIKI.models.navigation.getAuthorizedItems(WIKI.cache.get(`nav:sidebar:${locale}`), groups)
  49. }
  50. } else {
  51. WIKI.logger.warn('Site Navigation is missing or corrupted.')
  52. return []
  53. }
  54. }
  55. static getAuthorizedItems(tree = [], groups = []) {
  56. return _.filter(tree, leaf => {
  57. return leaf.visibilityMode === 'all' || _.intersection(leaf.visibilityGroups, groups).length > 0
  58. })
  59. }
  60. }