assetFolders.js 1.79 KB
Newer Older
1
const Model = require('objection').Model
Nick's avatar
Nick committed
2 3 4
const _ = require('lodash')

/* global WIKI */
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

/**
 * Users model
 */
module.exports = class AssetFolder extends Model {
  static get tableName() { return 'assetFolders' }

  static get jsonSchema () {
    return {
      type: 'object',

      properties: {
        id: {type: 'integer'},
        name: {type: 'string'},
        slug: {type: 'string'}
      }
    }
  }

  static get relationMappings() {
    return {
      parent: {
        relation: Model.BelongsToOneRelation,
        modelClass: AssetFolder,
        join: {
          from: 'assetFolders.folderId',
          to: 'assetFolders.id'
        }
      }
    }
  }
Nick's avatar
Nick committed
36

Nick's avatar
Nick committed
37 38 39 40 41
  /**
   * Get full folder hierarchy starting from specified folder to root
   *
   * @param {Number} folderId Id of the folder
   */
42
  static async getHierarchy (folderId) {
Nick's avatar
Nick committed
43
    const hier = await WIKI.models.knex.withRecursive('ancestors', qb => {
Nick's avatar
Nick committed
44 45 46 47
      qb.select('id', 'name', 'slug', 'parentId').from('assetFolders').where('id', folderId).union(sqb => {
        sqb.select('a.id', 'a.name', 'a.slug', 'a.parentId').from('assetFolders AS a').join('ancestors', 'ancestors.parentId', 'a.id')
      })
    }).select('*').from('ancestors')
Nick's avatar
Nick committed
48 49
    // The ancestors are from children to grandparents, must reverse for correct path order.
    return _.reverse(hier)
Nick's avatar
Nick committed
50
  }
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

  /**
   * Get full folder paths
   */
  static async getAllPaths () {
    const all = await WIKI.models.assetFolders.query()
    let folders = {}
    all.forEach(fld => {
      _.set(folders, fld.id, fld.slug)
      let parentId = fld.parentId
      while (parentId !== null || parentId > 0) {
        const parent = _.find(all, ['id', parentId])
        _.set(folders, fld.id, `${parent.slug}/${_.get(folders, fld.id)}`)
        parentId = parent.parentId
      }
    })
    return folders
  }
69
}