summaryrefslogtreecommitdiffstats
path: root/server
diff options
context:
space:
mode:
authorUdo Walter2018-12-04 17:41:15 +0100
committerUdo Walter2018-12-04 17:41:15 +0100
commit6bc320dddf45a88976ceb5fb17cf149d8b1e9e1b (patch)
tree5edcf1f2608624dd61d677fef8a2017edca01241 /server
parenteslint fix :) (diff)
downloadbas-6bc320dddf45a88976ceb5fb17cf149d8b1e9e1b.tar.gz
bas-6bc320dddf45a88976ceb5fb17cf149d8b1e9e1b.tar.xz
bas-6bc320dddf45a88976ceb5fb17cf149d8b1e9e1b.zip
[groups,clients,configurator] api rework to the new format
Diffstat (limited to 'server')
-rw-r--r--server/api/clients.js99
-rw-r--r--server/api/configurator.js125
-rw-r--r--server/api/groups.js177
-rw-r--r--server/app.js6
-rw-r--r--server/lib/grouputil.js21
-rw-r--r--server/package-lock.json5
-rw-r--r--server/package.json1
7 files changed, 242 insertions, 192 deletions
diff --git a/server/api/clients.js b/server/api/clients.js
index 147314d..35c2648 100644
--- a/server/api/clients.js
+++ b/server/api/clients.js
@@ -3,50 +3,63 @@ var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
var io = require(path.join(__appdir, 'lib', 'socketio'))
const backendHelper = require(path.join(__appdir, 'lib', 'external-backends', 'backendhelper'))
+var express = require('express')
+const { decorateApp } = require('@awaitjs/express');
+var router = decorateApp(express.Router())
-// GET Requests
-module.exports.get = {
- getList: function (req, res) {
- db.client.findAll({ attributes: ['id', 'name'], order: [['name', 'ASC']] }).then(list => {
- res.send(list)
- })
- },
-
- // 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 => {
- if (client) res.send(client)
- else res.status(404).end()
- })
- }
-}
-
-// POST Requests
-module.exports.post = {
- // create client or update information of a client (returns id)
- save: function (req, res) {
- if (req.body.id > 0) {
- db.client.findOne({ where: { id: req.body.id } }).then(client => {
- if (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: req.body.id }) })
- } else { res.status(404).end() }
- })
- } else {
- db.client.create(req.body.info).then(client => {
- io.in('broadcast newClient').emit('notifications newAlert', { type: 'info', text: 'New client!' })
- if (req.body.groupIds) client.setGroups(req.body.groupIds).then(() => { res.send({ id: client.id }) })
- })
- }
- },
+// ############################################################################
+// ########################### GET requests #################################
+
+router.getAsync('', async (req, res) => {
+ const clients = await db.client.findAll({ order: [['name', 'ASC']] })
+ res.send(clients)
+})
- // delete clients
- delete: async function (req, res) {
+router.getAsync('/:id', async (req, res) => {
+ const client = await db.client.findOne({ where: { id: req.params.id }, include: ['groups'] })
+ console.log(req.params.id)
+ if (client) res.status(200).send(client)
+ else res.status(404).end()
+})
+
+// ############################################################################
+// ########################## POST requests #################################
+
+router.postAsync(['', '/:id'], async (req, res) => {
+ if (req.query.delete !== undefined && req.query.delete !== 'false') {
await backendHelper.deleteClients(req.body.ids)
- db.client.destroy({ where: { id: req.body.ids } }).then(count => {
- res.send({ count })
- })
+ const count = await db.client.destroy({ where: { id: req.body.ids } })
+ res.status(200).send({ count })
+ } else {
+ let client
+ if (req.params.id === undefined) {
+ client = await db.client.create(req.body.data)
+ io.in('broadcast newClient').emit('notifications newAlert', { type: 'info', text: 'New client!' })
+ }
+ else {
+ client = await db.client.findOne({ where: { id: req.params.id } })
+ console.log('asd')
+ if (client) await client.update(req.body.data)
+ }
+ if (client) {
+ await client.setGroups(req.body.groupIds)
+ res.status(200).send({ id: client.id })
+ } else {
+ res.status(404).end()
+ }
}
-}
+})
+
+// ############################################################################
+// ########################## DELETE requests ###############################
+
+router.delete('/:id', async (req, res) => {
+ const count = await db.client.destroy({ where: { id: req.params.id } })
+ if (count) res.status(200).end()
+ else res.status(404).end()
+})
+
+// ############################################################################
+// ############################################################################
+
+module.exports.router = router
diff --git a/server/api/configurator.js b/server/api/configurator.js
index 250471b..d0e4531 100644
--- a/server/api/configurator.js
+++ b/server/api/configurator.js
@@ -1,79 +1,98 @@
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
+var Sequelize = require('sequelize')
var express = require('express')
-var router = express.Router()
+const { decorateApp } = require('@awaitjs/express');
+var router = decorateApp(express.Router())
-router.get('/configs', (req, res) => {
- db.config.findAll().then(configs => {
- res.send(configs)
- })
+// ############################################################################
+// ########################### GET requests #################################
+
+router.getAsync('/configs', async (req, res) => {
+ const configs = await db.config.findAll({ order: [['name', 'ASC']] })
+ res.status(200).send(configs)
})
-router.get('/entries', (req, res) => {
- db.entry.findAll().then(entries => {
- res.send(entries)
- })
+router.getAsync('/entries', async (req, res) => {
+ const entries = await db.entry.findAll({ order: [['name', 'ASC']] })
+ res.status(200).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.getAsync('/configs/:id/entries', async (req, res) => {
+ var config = await db.config.findOne({
+ where: { id: req.params.id }, include: ['entries'],
+ order: [[db.config.associations.entries, db.config.associations.entries.through, 'sortValue', 'ASC']]
+ })
+ if (config) res.status(200).send(config.entries)
+ else res.status(404).end()
})
-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
- }
+// ############################################################################
+// ########################## POST requests #################################
- var config = null
- if (req.params.id > 0) {
- config = await db.config.findOne({ where: { id: req.params.id } })
- if (config) await config.update(item)
+router.postAsync(['/configs', '/configs/:id'], async (req, res) => {
+ if (req.query.delete !== undefined && req.query.delete !== 'false') {
+ const count = await db.config.destroy({ where: { id: req.body.ids } })
+ res.status(200).send({ count })
} 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)
+ let config
+ if (req.params.id === undefined) config = await db.config.create(req.body.data)
+ else {
+ config = await db.config.findOne({ where: { id: req.params.id } })
+ if (config) await config.update(req.body.data)
+ }
+ if (config) {
+ await config.setEntries([])
+ if (req.body.entries.length > 0) {
+ const 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.status(200).send({ id: config.id })
+ } else {
+ res.status(404).end()
}
- 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)
+router.postAsync(['/entries', '/entries/:id'], async (req, res) => {
+ if (req.query.delete !== undefined && req.query.delete !== 'false') {
+ const count = await db.entry.destroy({ where: { id: req.body.ids } })
+ res.status(200).send({ count })
} else {
- entry = await db.entry.create(item)
- }
- if (entry) {
- res.send({ id: entry.id })
+ let entry
+ if (req.params.id === undefined) entry = await db.entry.create(req.body.data)
+ else {
+ entry = await db.entry.findOne({ where: { id: req.params.id } })
+ if (entry) await entry.update(req.body.data)
+ }
+ if (entry) {
+ res.status(200).send({ id: entry.id })
+ } else {
+ res.status(404).end()
+ }
}
- res.end()
})
-router.post('/delete/configs', (req, res) => {
- db.config.destroy({ where: { id: req.body.ids } }).then(count => { res.send({ count }) })
+// ############################################################################
+// ########################## DELETE requests ###############################
+
+router.deleteAsync('/configs/:id', async (req, res) => {
+ const count = await db.config.destroy({ where: { id: req.params.id } })
+ if (count) res.status(200).end()
+ else res.status(404).end()
})
-router.post('/delete/entries', (req, res) => {
- db.entry.destroy({ where: { id: req.body.ids } }).then(count => { res.send({ count }) })
+router.deleteAsync('/entries/:id', async (req, res) => {
+ const count = await db.entry.destroy({ where: { id: req.params.id } })
+ if (count) res.status(200).end()
+ else res.status(404).end()
})
+// ############################################################################
+// ############################################################################
+
module.exports.router = router
diff --git a/server/api/groups.js b/server/api/groups.js
index ddaed18..f1825cc 100644
--- a/server/api/groups.js
+++ b/server/api/groups.js
@@ -1,111 +1,102 @@
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
+var groupUtil = require(path.join(__appdir, 'lib', 'grouputil'))
+var express = require('express')
+const { decorateApp } = require('@awaitjs/express');
+var router = decorateApp(express.Router())
-async function getAllChildren (groups, knownGroupIds = []) {
- groups = groups.filter(subgroup => !knownGroupIds.includes(subgroup.id))
- var groupIds = groups.map(g => g.id)
- knownGroupIds = [...knownGroupIds, ...groupIds]
- var [subgroups, clients] = await Promise.all([
- db.group.findAll({ where: { '$parents.id$': groupIds }, include: ['parents'] }),
- db.client.findAll({ where: { '$groups.id$': groupIds }, include: ['groups'] })
- ])
- if (subgroups.length > 0) {
- var subChildren = await getAllChildren(subgroups, knownGroupIds)
- subgroups = [...subgroups, ...subChildren.subgroups]
- clients = [...clients, ...subChildren.clients]
+// ############################################################################
+// ########################### GET requests #################################
+
+router.getAsync('', async (req, res) => {
+ const groups = await db.group.findAll({ order: [['name', 'ASC']] })
+ res.send(groups)
+})
+
+router.getAsync('/:id', async (req, res) => {
+ const all = req.query.all !== undefined && req.query.all !== 'false'
+ if (req.params.id > 0) {
+ const group = await db.group.findOne({ where: { id: req.params.id }, include: ['parents', 'subgroups', 'clients'] })
+ if (group) {
+ if (all) res.status(200).send({ ...group.get({ plain: true }), ...await groupUtil.getAllChildren([group]) })
+ else res.status(200).send(group)
+ } else {
+ res.status(404).end()
+ }
+ } else {
+ const [subgroups, clients] = await Promise.all([
+ db.group.findAll(all ? {} : { where: { '$parents.id$': null }, include: ['parents'] }),
+ db.client.findAll(all ? {} : { where: { '$groups.id$': null }, include: ['groups'] })
+ ])
+ res.send({ id: 0, subgroups, clients })
}
- return { subgroups, clients }
-}
+})
+
-// 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', 'description'], order: [['name', 'ASC']] }).then(list => {
- res.send(list)
- })
- },
+// ############################################################################
+// ########################## POST requests #################################
- // get name, description, parents, subgroups and clients of a group (by id)
- getGroup: function (req, res) {
- const all = req.query.all === 'true'
- if (req.query.id > 0) {
- db.group.findOne({ where: { id: req.query.id }, include: ['parents', 'subgroups', 'clients'] }).then(async group => {
- if (group) {
- if (all) res.send({ ...group.get({ plain: true }), ...await getAllChildren([group]) })
- else res.send(group)
- } else {
- res.status(404).end()
- }
- })
+router.postAsync(['', '/:id'], async (req, res) => {
+ if (req.query.delete !== undefined && req.query.delete !== 'false') {
+ const count = await db.group.destroy({ where: { id: req.body.ids } })
+ res.status(200).send({ count })
+ } else {
+ let group
+ if (req.params.id === undefined) group = await db.group.create(req.body.data)
+ else {
+ group = await db.group.findOne({ where: { id: req.params.id } })
+ if (group) await group.update(req.body.data)
+ }
+ if (group) {
+ await group.setParents(req.body.parentIds)
+ res.status(200).send({ id: group.id })
} else {
- Promise.all([db.group.findAll(all ? {} : { where: { '$parents.id$': null }, include: ['parents'] }),
- db.client.findAll(all ? {} : { where: { '$groups.id$': null }, include: ['groups'] })]).then(result => {
- res.send({ id: 0, subgroups: result[0], clients: result[1] })
- })
+ res.status(404).end()
}
}
-}
+})
-// POST Requests
-module.exports.post = {
- // create group or update information of a group (returns id)
- save: function (req, res) {
- if (req.body.id > 0) {
- db.group.findOne({ where: { id: req.body.id } }).then(group => {
- if (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: req.body.id }) })
- } else { res.status(404).end() }
- })
+router.postAsync('/:id/subgroups', async (req, res) => {
+ const group = await db.group.findOne({ where: { id: req.params.id } })
+ if (group) {
+ if (req.query.delete !== undefined && req.query.delete !== 'false') {
+ const count = await group.removeSubgroups(req.body.ids)
+ res.status(200).send({ count })
} else {
- db.group.create(req.body.info).then(group => {
- if (req.body.parentIds) group.setParents(req.body.parentIds).then(() => { res.send({ id: group.id }) })
- })
+ const count = await group.addSubgroups(req.body.ids)
+ res.status(200).send({ count })
}
- },
+ } else {
+ res.status(404).end()
+ }
+})
- // delete groups
- delete: function (req, res) {
- db.group.destroy({ where: { id: req.body.ids } }).then(count => { res.send({ count }) })
- },
+router.postAsync('/:id/clients', async (req, res) => {
+ const group = await db.group.findOne({ where: { id: req.params.id } })
+ if (group) {
+ if (req.query.delete !== undefined && req.query.delete !== 'false') {
+ const count = await group.removeClients(req.body.ids)
+ res.status(200).send({ count })
+ } else {
+ const count = await group.addClients(req.body.ids)
+ res.status(200).send({ count })
+ }
+ } else {
+ res.status(404).end()
+ }
+})
- // remove subgroups from a group
- removeSubgroups: function (req, res) {
- db.group.findOne({ where: { id: req.body.id } }).then(group => {
- if (group) {
- group.removeSubgroups(req.body.ids).then(() => { res.end() })
- } else { res.status(404).end() }
- })
- },
+// ############################################################################
+// ########################## DELETE requests ###############################
- // remove clients from a group
- removeClients: function (req, res) {
- db.group.findOne({ where: { id: req.body.id } }).then(group => {
- if (group) {
- group.removeClients(req.body.ids).then(() => { res.end() })
- } else { res.status(404).end() }
- })
- },
+router.delete('/:id', async (req, res) => {
+ const count = await db.group.destroy({ where: { id: req.params.id } })
+ if (count) res.status(200).end()
+ else res.status(404).end()
+})
- // add subgroups to a group
- addSubgroups: function (req, res) {
- db.group.findOne({ where: { id: req.body.id } }).then(group => {
- if (group) {
- group.addSubgroups(req.body.ids).then(() => { res.end() })
- } else { res.status(404).end() }
- })
- },
+// ############################################################################
+// ############################################################################
- // add clients to a group
- addClients: function (req, res) {
- db.group.findOne({ where: { id: req.body.id } }).then(group => {
- if (group) {
- group.addClients(req.body.ids).then(() => { res.end() })
- } else { res.status(404).end() }
- })
- }
-}
+module.exports.router = router
diff --git a/server/app.js b/server/app.js
index 4e72fa5..d026337 100644
--- a/server/app.js
+++ b/server/app.js
@@ -1,12 +1,10 @@
+var path = require('path')
var createError = require('http-errors')
var express = require('express')
var cookieParser = require('cookie-parser')
var compression = require('compression')
var fileUpload = require('express-fileupload')
-var path = require('path')
-// var fs = require('fs')
-
var app = express()
global.__appdir = __dirname
@@ -45,6 +43,8 @@ app.use(function (req, res, next) {
// error handler
app.use(function (err, req, res, next) {
+ console.log(err)
+
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
diff --git a/server/lib/grouputil.js b/server/lib/grouputil.js
new file mode 100644
index 0000000..311eb7e
--- /dev/null
+++ b/server/lib/grouputil.js
@@ -0,0 +1,21 @@
+/* global __appdir */
+var path = require('path')
+var db = require(path.join(__appdir, 'lib', 'sequelize'))
+
+async function getAllChildren (groups, knownGroupIds = []) {
+ groups = groups.filter(subgroup => !knownGroupIds.includes(subgroup.id))
+ var groupIds = groups.map(g => g.id)
+ knownGroupIds = [...knownGroupIds, ...groupIds]
+ var [subgroups, clients] = await Promise.all([
+ db.group.findAll({ where: { '$parents.id$': groupIds }, include: ['parents'] }),
+ db.client.findAll({ where: { '$groups.id$': groupIds }, include: ['groups'] })
+ ])
+ if (subgroups.length > 0) {
+ var subChildren = await getAllChildren(subgroups, knownGroupIds)
+ subgroups = [...subgroups, ...subChildren.subgroups]
+ clients = [...clients, ...subChildren.clients]
+ }
+ return { subgroups, clients }
+}
+
+module.exports.getAllChildren = getAllChildren \ No newline at end of file
diff --git a/server/package-lock.json b/server/package-lock.json
index 14fe543..25133c1 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -4,6 +4,11 @@
"lockfileVersion": 1,
"requires": true,
"dependencies": {
+ "@awaitjs/express": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/@awaitjs/express/-/express-0.1.4.tgz",
+ "integrity": "sha512-ueg4Nh3dr+/Djm8tequ9lwwT6a3QsjFzxQ2Mh3rAdF3FTe5FV4L/5ip42bVOB5aBIcFsrOU18eG4TX+OWXLS8g=="
+ },
"@babel/code-frame": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz",
diff --git a/server/package.json b/server/package.json
index 78ed4e6..9f46c0c 100644
--- a/server/package.json
+++ b/server/package.json
@@ -7,6 +7,7 @@
"start": "node ./bin/www"
},
"dependencies": {
+ "@awaitjs/express": "^0.1.4",
"axios": "^0.18.0",
"compression": "^1.7.3",
"cookie-parser": "^1.4.3",