navigation.mjs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { Model } from 'objection'
  2. import { has, intersection } 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. if (!result) { return [] }
  20. return result.items.filter(item => {
  21. return !item.visibilityGroups?.length || intersection(item.visibilityGroups, userGroups).length > 0
  22. }).map(item => {
  23. if (!item.children || item.children?.length < 1) { return item }
  24. return {
  25. ...item,
  26. children: item.children.filter(child => {
  27. return !child.visibilityGroups?.length || intersection(child.visibilityGroups, userGroups).length > 0
  28. })
  29. }
  30. })
  31. }
  32. static async getTree({ cache = false, locale = 'en', groups = [], bypassAuth = false } = {}) {
  33. if (cache) {
  34. const navTreeCached = await WIKI.cache.get(`nav:sidebar:${locale}`)
  35. if (navTreeCached) {
  36. return bypassAuth ? navTreeCached : WIKI.db.navigation.getAuthorizedItems(navTreeCached, groups)
  37. }
  38. }
  39. const navTree = await WIKI.db.navigation.query().findOne('key', `site`)
  40. if (navTree) {
  41. // Check for pre-2.3 format
  42. if (has(navTree.config[0], 'kind')) {
  43. navTree.config = [{
  44. locale: 'en',
  45. items: navTree.config.map(item => ({
  46. ...item,
  47. visibilityMode: 'all',
  48. visibilityGroups: []
  49. }))
  50. }]
  51. }
  52. for (const tree of navTree.config) {
  53. if (cache) {
  54. await WIKI.cache.set(`nav:sidebar:${tree.locale}`, tree.items, 300)
  55. }
  56. }
  57. if (bypassAuth) {
  58. return locale === 'all' ? navTree.config : WIKI.cache.get(`nav:sidebar:${locale}`)
  59. } else {
  60. return locale === 'all' ? WIKI.db.navigation.getAuthorizedItems(navTree.config, groups) : WIKI.db.navigation.getAuthorizedItems(WIKI.cache.get(`nav:sidebar:${locale}`), groups)
  61. }
  62. } else {
  63. WIKI.logger.warn('Site Navigation is missing or corrupted.')
  64. return []
  65. }
  66. }
  67. static getAuthorizedItems(tree = [], groups = []) {
  68. return tree.filter(leaf => {
  69. return leaf.visibilityMode === 'all' || intersection(leaf.visibilityGroups, groups).length > 0
  70. })
  71. }
  72. }