summaryrefslogtreecommitdiffstats
path: root/server/api/configurator.js
blob: 250471baa3d1825aa3a092109be267983ae2541d (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
var express = require('express')
var router = express.Router()

router.get('/configs', (req, res) => {
  db.config.findAll().then(configs => {
    res.send(configs)
  })
})

router.get('/entries', (req, res) => {
  db.entry.findAll().then(entries => {
    res.send(entries)
  })
})

router.get('/configs/:id/entries', async (req, res) => {
  var config = await db.config.findOne({ where: { id: req.params.id } })
  var entries = await config.getEntries({ order: [[['entries'], 'sortValue', 'ASC']] })
  res.send(entries)
})

router.post(['/configs', '/configs/:id'], async (req, res) => {
  var item = {
    name: req.body.name,
    description: req.body.description,
    defaultEntry: req.body.defaultEntry,
    timeout: req.body.timeout > 0 ? req.body.timeout : null,
    script: req.body.script
  }

  var config = null
  if (req.params.id > 0) {
    config = await db.config.findOne({ where: { id: req.params.id } })
    if (config) await config.update(item)
  } else {
    config = await db.config.create(item)
  }

  if (config) {
    await config.setEntries([])
    if (req.body.entries.length > 0) {
      var promises = []
      req.body.entries.forEach((entry, index) => {
        promises.push(config.addEntry(entry.id, { through: { sortValue: index, customName: entry.customName, keyBind: entry.keyBind } }))
      })
      await Promise.all(promises)
    }
    res.send({ id: config.id })
  }
  res.end()
})

router.post(['/entries', '/entries/:id'], async (req, res) => {
  var item = { name: req.body.name, script: req.body.script }
  var entry = null
  if (req.params.id > 0) {
    entry = await db.entry.findOne({ where: { id: req.params.id } })
    if (entry) await entry.update(item)
  } else {
    entry = await db.entry.create(item)
  }
  if (entry) {
    res.send({ id: entry.id })
  }
  res.end()
})

router.post('/delete/configs', (req, res) => {
  db.config.destroy({ where: { id: req.body.ids } }).then(count => { res.send({ count }) })
})

router.post('/delete/entries', (req, res) => {
  db.entry.destroy({ where: { id: req.body.ids } }).then(count => { res.send({ count }) })
})

module.exports.router = router