/* global __appdir */ var path = require('path') var db = require(path.join(__appdir, 'lib', 'sequelize')) var express = require('express') const { decorateApp } = require('@awaitjs/express') var router = decorateApp(express.Router()) const httpResponse = require(path.join(__appdir, 'lib', 'httpresponse')) // ############################################################################ // ########################### GET requests ################################# router.getAsync('', async (req, res) => { const entries = await db.entry.findAll() res.status(200).send(entries) }) router.getAsync('/:id', async (req, res) => { if (!(req.params.id > 0)) httpResponse.invalidId(res) const entry = await db.entry.findOne({ where: { id: req.params.id } }) if (entry) res.status(200).send(entry) else httpResponse.notFound(res, req.params.id) }) // ############################################################################ // ########################## POST requests ################################# router.postAsync(['', '/:id'], async (req, res) => { if (req.query.delete !== undefined && req.query.delete !== 'false') { if (!Array.isArray(req.body.ids)) return httpResponse.invalidBodyValue(res, 'ids', 'an array') const count = await db.entry.destroy({ where: { id: req.body.ids } }) httpResponse.successBatch(res, 'deleted', ['ipxe entry', 'ipxe entries'], count) } else { let entry let action = 'updated' if (req.params.id === undefined) { entry = await db.entry.create(req.body.data) action = 'created' } else if (req.params.id > 0) { entry = await db.entry.findOne({ where: { id: req.params.id } }) if (!entry) return httpResponse.notFound(res, req.params.id) else await entry.update(req.body.data) } else { return httpResponse.invalidId(res) } httpResponse.success(res, action, 'ipxe entry', entry.id) } }) // ############################################################################ // ########################## DELETE requests ############################### router.deleteAsync('/:id', async (req, res) => { if (!(req.params.id > 0)) return httpResponse.invalidId(res) const count = await db.entry.destroy({ where: { id: req.params.id } }) if (count) httpResponse.success(res, 'deleted', ['ipxe entry', 'ipxe entries'], req.params.id) else httpResponse.notFound(res, req.params.id) }) // ############################################################################ // ############################################################################ module.exports.router = router