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.

51 lines
1.3 KiB

  1. const Model = require('objection').Model
  2. const _ = require('lodash')
  3. /* global WIKI */
  4. /**
  5. * Users model
  6. */
  7. module.exports = class AssetFolder extends Model {
  8. static get tableName() { return 'assetFolders' }
  9. static get jsonSchema () {
  10. return {
  11. type: 'object',
  12. properties: {
  13. id: {type: 'integer'},
  14. name: {type: 'string'},
  15. slug: {type: 'string'}
  16. }
  17. }
  18. }
  19. static get relationMappings() {
  20. return {
  21. parent: {
  22. relation: Model.BelongsToOneRelation,
  23. modelClass: AssetFolder,
  24. join: {
  25. from: 'assetFolders.folderId',
  26. to: 'assetFolders.id'
  27. }
  28. }
  29. }
  30. }
  31. /**
  32. * Get full folder hierarchy starting from specified folder to root
  33. *
  34. * @param {Number} folderId Id of the folder
  35. */
  36. static async getHierarchy(folderId) {
  37. const hier = await WIKI.models.knex.withRecursive('ancestors', qb => {
  38. qb.select('id', 'name', 'slug', 'parentId').from('assetFolders').where('id', folderId).union(sqb => {
  39. sqb.select('a.id', 'a.name', 'a.slug', 'a.parentId').from('assetFolders AS a').join('ancestors', 'ancestors.parentId', 'a.id')
  40. })
  41. }).select('*').from('ancestors')
  42. // The ancestors are from children to grandparents, must reverse for correct path order.
  43. return _.reverse(hier)
  44. }
  45. }