Files
cgm-remote-monitor/lib/api/devicestatus/index.js
T
2018-08-08 21:55:22 -05:00

108 lines
2.8 KiB
JavaScript

'use strict';
var consts = require('../../constants');
var ID_PATTERN = /^[a-f\d]{24}$/;
function isId(value) {
return value && ID_PATTERN.test(value) && value.length === 24;
}
function configure (app, wares, ctx) {
var express = require('express'),
api = express.Router( );
// invoke common middleware
api.use(wares.sendJSONStatus);
// text body types get handled as raw buffer stream
api.use(wares.bodyParser.raw( ));
// json body types get handled as parsed json
api.use(wares.bodyParser.json( ));
// also support url-encoded content-type
api.use(wares.bodyParser.urlencoded({ extended: true }));
api.use(ctx.authorization.isPermitted('api:devicestatus:read'));
// List settings available
api.get('/devicestatus/', function(req, res) {
var q = req.query;
if (!q.count) {
q.count = 10;
}
ctx.devicestatus.list(q, function (err, results) {
return res.json(results);
});
});
/**
* @function delete_records
* Delete entries. The query logic works the same way as find/list. This
* endpoint uses same search logic to remove records from the database.
*/
function delete_records(req, res, next) {
// bias towards model, but allow expressing a preference
if (!req.model) {
req.model = ctx.devicestatus;
}
var query = req.query;
if (!query.count) {
query.count = 10
}
console.log('Delete records with query: ', query);
// remove using the query
req.model.remove(query, function(err, stat) {
if (err) {
return next(err);
}
// yield some information about success of operation
res.json(stat);
return next();
});
}
function config_authed (app, api, wares, ctx) {
function doPost (req, res) {
var obj = req.body;
ctx.devicestatus.create(obj, function (err, created) {
if (err) {
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
} else {
res.json(created);
}
});
}
api.post('/devicestatus/', ctx.authorization.isPermitted('api:devicestatus:create'), doPost);
api.delete('/devicestatus/:_id', ctx.authorization.isPermitted('api:devicestatus:delete'), function(req, res) {
console.log('Deleting id: ' + req.params._id);
ctx.devicestatus.remove(req.params._id, function (err, removed) {
if (err) {
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
} else {
res.json(removed);
}
});
});
// delete record
api.delete('/devicestatus/', ctx.authorization.isPermitted('api:devicestatus:delete'), function(req, res, next) {
next();
}, delete_records);
}
if (app.enabled('api') || true /*TODO: auth disabled for quick UI testing...*/) {
config_authed(app, api, wares, ctx);
}
return api;
}
module.exports = configure;