summaryrefslogblamecommitdiffstats
path: root/server/api/groups.js
blob: 43abe4eb6935a783fca6818ee078ae170a6fe378 (plain) (tree)
1
2
3
4
5
6
7
8
9



                                                         

                      
                                                    
                                
                                                                                             


                    
 






                                     



                                                                                                

      
 



                                                                                                                   


      
 

                       
                                                               
                                       
                                                   

                                                             



                                                                                   

            


                                                                                                               
     

   
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))

// GET Requests
module.exports.get = {
  // get a list containing id and name of all groups
  getList: function (req, res) {
    db.group.findAll({ attributes: ['id', 'name'], order: [['name', 'ASC']] }).then(list => {
      res.send(list)
    })
  },

  // get all groups
  getAll: function (req, res) {
    db.group.findAll().then(list => {
      res.send(list)
    })
  },

  // get all groups that have no parents
  getTopLevel: function (req, res) {
    db.group.findAll({ where: { '$parents.id$': null }, include: ['parents'] }).then(groups => {
      res.send(groups)
    })
  },

  // get name, description, parents, subgroups and clients of a group (by id)
  getGroup: function (req, res) {
    db.group.findOne({ where: { id: req.query.id }, include: ['parents', 'subgroups', 'clients'] }).then(group => {
      res.send(group)
    })
  }
}

// POST Requests
module.exports.post = {
  // create group or update information of a group (returns id)
  updateOrCreate: function (req, res) {
    const id = req.body.id > 0 ? req.body.id : null
    if (id) {
      db.group.findOne({ where: { id: id } }).then(group => {
        var promises = []
        if (req.body.info) promises.push([group.update(req.body.info)])
        if (req.body.parentIds) promises.push(group.setParents(req.body.parentIds))
        Promise.all(promises).then(() => { res.send({id}) })
      })
    } else {
      db.group.create(req.body.info).then(group => {
        if (req.body.parentIds) group.setParents(req.body.parentIds).then(() => { res.send({ id: group.id }) })
      })
    }
  }
}