@arisan/data-api
Version:
The Universal Database API Gateway for CLIO's Modules
84 lines (77 loc) • 2.88 kB
JavaScript
; // eslint-disable-line strict
/* Platform Libraries */
const ipaddr = require('ipaddr.js');
const ObjectID = require('mongodb').ObjectID;
const BaseHandler = require('./base-handler');
class ObserverHandler extends BaseHandler {
constructor(logger, observers) {
super(logger);
this.observers = observers;
this.debug(`${ this.constructor.name } Constructed`);
}
createObserver(req, res) {
const tag = 'createObserver> ';
this.debug(`${ tag }Body ${ JSON.stringify(req.body, null, 2) }`);
const now = new Date();
const observer = {
public_ip: req.body.publicIp,
private_ip: ipaddr.process(req.ip).toString(),
port: req.body.port,
created: now,
updated: now
};
if (!this.checkValidPublicIp(observer.public_ip, res, tag)) {
return;
}
if (!this.checkValidPort(observer.port, res, tag)) {
return;
}
this.observers.insertOne(observer, (insertOneErr, insertOneRes) => {
if (insertOneErr) {
this.handleError(res, 500, `${ tag }${ insertOneErr.message }`);
return;
}
this.info(`${ tag }ID ${ insertOneRes.insertedId } Registered`);
res.type('text/plain');
res.status(201).send(new Buffer(`${ insertOneRes.insertedId }`));
});
}
updateObserver(req, res) {
const tag = 'updateObserver> ';
const observerId = req.params.observerId;
this.debug(`${ tag }ID ${ observerId } Body ${ JSON.stringify(req.body, null, 2) }`);
let objectId;
try {
objectId = new ObjectID(observerId);
} catch (err) {
this.handleError(res, 400, `${ tag }${ err.message }`);
return;
}
if (!this.checkRequestBodyProperties(req.body, res, tag, observerId, 'streamIds', 'cpuUsagePercentage', 'memoryUsagePercentage', 'hddUsageKB', 'hddTotalKB', 'netUploadBytesPerSecond', 'netDownloadBytesPerSecond')) {
return;
}
const diff = {
updated: new Date(),
stream_ids: req.body.streamIds,
cpu_load: Math.ceil(req.body.cpuUsagePercentage * 100),
mem_load: Math.ceil(req.body.memoryUsagePercentage),
hdd_load: Math.ceil(req.body.hddUsageKB * 100 / req.body.hddTotalKB),
upload_kbps: Math.ceil(req.body.netUploadBytesPerSecond * 8 / 1024),
download_kbps: Math.ceil(req.body.netDownloadBytesPerSecond * 8 / 1024)
};
this.observers.updateOne({ _id: objectId }, { $set: diff }, (updateOneErr, updateOneRes) => {
if (updateOneErr) {
this.handleError(res, 500, `${ tag }${ updateOneErr.message }`);
return;
}
if (!updateOneRes.matchedCount) {
this.handleError(res, 404, `${ tag }ID ${ observerId } Not Found`);
return;
}
this.info(`${ tag }ID ${ objectId } Updated`);
res.sendStatus(200);
});
}
}
module.exports = ObserverHandler;
//# sourceMappingURL=observer-handler.js.map