summaryrefslogtreecommitdiffstats
path: root/server/lib/grouputil.js
blob: 75da2092b9fb1fa2133a87ea4c53a11762c05e43 (plain) (blame)
1
2
3
4
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
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))

async function getAllChildren (groups) {
  return await getAllChildrenByIds(groups.map(x => x.id), {}, {})
}

async function getAllChildrenByIds (groupIds, knownGroupMap, knownClientMap) {
  let [subgroups, clients] = await Promise.all([
    db.group.findAll({ where: { '$parents.id$': groupIds }, include: ['parents'] }),
    db.client.findAll({ where: { '$groups.id$': groupIds }, include: ['groups'] })
  ])

  subgroups = subgroups.filter(subgroup => !knownGroupMap[subgroup.id])
  clients = clients.filter(client => !knownClientMap[client.id])

  if (subgroups.length > 0) {
    let groupIds = subgroups.map(x => x.id)
    for (let i in groupIds) {
      knownGroupMap[groupIds[i]] = true
    }
    let clientIds = clients.map(x => x.id)
    for (let i in clientIds) {
      knownClientMap[clientIds[i]] = true
    }
    let subChildren = await getAllChildrenByIds(groupIds, knownGroupMap, knownClientMap)
    subgroups = [...subgroups, ...subChildren.subgroups]
    clients = [...clients, ...subChildren.clients]
  }

  return { subgroups, clients }
}

module.exports.getAllChildren = getAllChildren