/* global __appdir */ 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 ################################# router.getAsync('', async (req, res) => { const clients = await db.client.findAll({ order: [['name', 'ASC']] }) res.send(clients) }) router.getAsync('/:id', async (req, res) => { const client = await db.client.findOne({ where: { id: req.params.id }, include: ['groups'] }) 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) 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 } }) 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