summaryrefslogtreecommitdiffstats
path: root/server/api/clients.js
blob: 4f7ce1de60c5c60ca37c43d31855e4e3ea7867ea (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))

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

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

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

  // get name, description, ip, mac and uuid of a client (by id)
  getClient: function (req, res) {
    db.client.findOne({ where: { id: req.query.id }, include: ['groups'] }).then(client => {
      res.send(client)
    })
  }
}

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

  // delete clients
  delete: function (req, res) {
    db.client.destroy({ where: { id: req.body.ids } }).then(() => { res.end() })
  }
}