navigation.js 1.97 KB
Newer Older
1
const Model = require('objection').Model
NGPixel's avatar
NGPixel committed
2
const _ = require('lodash')
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

/* global WIKI */

/**
 * Navigation model
 */
module.exports = class Navigation extends Model {
  static get tableName() { return 'navigation' }
  static get idColumn() { return 'key' }

  static get jsonSchema () {
    return {
      type: 'object',
      required: ['key'],

      properties: {
        key: {type: 'string'},
20
        config: {type: 'array', items: {type: 'object'}}
21 22 23 24
      }
    }
  }

25
  static async getTree({ cache = false, locale = 'en', groups = [], bypassAuth = false } = {}) {
26
    if (cache) {
NGPixel's avatar
NGPixel committed
27
      const navTreeCached = await WIKI.cache.get(`nav:sidebar:${locale}`)
28
      if (navTreeCached) {
29
        return bypassAuth ? navTreeCached : WIKI.models.navigation.getAuthorizedItems(navTreeCached, groups)
30 31
      }
    }
32
    const navTree = await WIKI.models.navigation.query().findOne('key', `site`)
33
    if (navTree) {
34
      // Check for pre-2.3 format
NGPixel's avatar
NGPixel committed
35 36 37
      if (_.has(navTree.config[0], 'kind')) {
        navTree.config = [{
          locale: 'en',
38 39 40 41 42
          items: navTree.config.map(item => ({
            ...item,
            visibilityMode: 'all',
            visibilityGroups: []
          }))
NGPixel's avatar
NGPixel committed
43
        }]
44
      }
NGPixel's avatar
NGPixel committed
45 46 47 48 49 50

      for (const tree of navTree.config) {
        if (cache) {
          await WIKI.cache.set(`nav:sidebar:${tree.locale}`, tree.items, 300)
        }
      }
51 52 53 54 55
      if (bypassAuth) {
        return locale === 'all' ? navTree.config : WIKI.cache.get(`nav:sidebar:${locale}`)
      } else {
        return locale === 'all' ? WIKI.models.navigation.getAuthorizedItems(navTree.config, groups) : WIKI.models.navigation.getAuthorizedItems(WIKI.cache.get(`nav:sidebar:${locale}`), groups)
      }
56 57 58 59
    } else {
      WIKI.logger.warn('Site Navigation is missing or corrupted.')
      return []
    }
60
  }
61 62 63 64 65 66

  static getAuthorizedItems(tree = [], groups = []) {
    return _.filter(tree, leaf => {
      return leaf.visibilityMode === 'all' || _.intersection(leaf.visibilityGroups, groups).length > 0
    })
  }
67
}