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.

79 lines
2.2 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. let hier
  38. if (WIKI.config.db.type === 'mssql') {
  39. hier = await WIKI.models.knex.with('ancestors', qb => {
  40. qb.select('id', 'name', 'slug', 'parentId').from('assetFolders').where('id', folderId).unionAll(sqb => {
  41. sqb.select('a.id', 'a.name', 'a.slug', 'a.parentId').from('assetFolders AS a').join('ancestors', 'ancestors.parentId', 'a.id')
  42. })
  43. }).select('*').from('ancestors')
  44. }
  45. else {
  46. hier = await WIKI.models.knex.withRecursive('ancestors', qb => {
  47. qb.select('id', 'name', 'slug', 'parentId').from('assetFolders').where('id', folderId).union(sqb => {
  48. sqb.select('a.id', 'a.name', 'a.slug', 'a.parentId').from('assetFolders AS a').join('ancestors', 'ancestors.parentId', 'a.id')
  49. })
  50. }).select('*').from('ancestors')
  51. }
  52. // The ancestors are from children to grandparents, must reverse for correct path order.
  53. return _.reverse(hier)
  54. }
  55. /**
  56. * Get full folder paths
  57. */
  58. static async getAllPaths () {
  59. const all = await WIKI.models.assetFolders.query()
  60. let folders = {}
  61. all.forEach(fld => {
  62. _.set(folders, fld.id, fld.slug)
  63. let parentId = fld.parentId
  64. while (parentId !== null || parentId > 0) {
  65. const parent = _.find(all, ['id', parentId])
  66. _.set(folders, fld.id, `${parent.slug}/${_.get(folders, fld.id)}`)
  67. parentId = parent.parentId
  68. }
  69. })
  70. return folders
  71. }
  72. }