navigation.mjs 2.5 KB

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