@arisan/data-api
Version:
The Universal Database API Gateway for CLIO's Modules
91 lines (84 loc) • 2.81 kB
JavaScript
; // eslint-disable-line strict
/* Platform Libraries */
const ipaddr = require('ipaddr.js');
const ObjectID = require('mongodb').ObjectID;
/* Project Libraries */
const BaseHandler = require('./base-handler');
class StreamerHandler extends BaseHandler {
constructor(logger, streamers) {
super(logger);
this.streamers = streamers;
this.debug(`${ this.constructor.name } Constructed`);
}
createStreamer(req, res) {
const tag = 'createStreamer> ';
this.debug(`${ tag }Body ${ JSON.stringify(req.body, null, 2) }`);
const now = new Date();
const streamer = {
public_ip: req.body.publicIp,
private_ip: ipaddr.process(req.ip).toString(),
port: req.body.port,
created: now,
updated: now
};
if (!this.checkValidPublicIp(streamer.public_ip, res, tag)) {
return;
}
if (!this.checkValidPort(streamer.port, res, tag)) {
return;
}
this.streamers.insertOne(streamer, (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 }`));
});
}
/**
* @param {Object} req
* @param {string} req.params.streamerId
* @param {number} req.body.cpuLoad
* @param {Object} req.body.mem
* @param {Object} res
*/
updateStreamer(req, res) {
const tag = 'updateStreamer> ';
const streamerId = req.params.streamerId;
this.debug(`${ tag }ID ${ streamerId } Body ${ JSON.stringify(req.body, null, 2) }`);
let objectId;
try {
objectId = new ObjectID(streamerId);
} catch (err) {
this.handleError(res, 400, `${ tag }${ err.message }`);
return;
}
if (!this.checkRequestBodyProperties(req.body, res, tag, streamerId, 'streamIds', 'cpuLoad', 'mem')) {
return;
}
const diff = {
updated: new Date(),
stream_ids: req.body.streamIds,
cpu_load: Math.ceil(req.body.cpuLoad),
mem_load: Math.ceil(req.body.mem.load),
mem_current: Math.ceil(req.body.mem.current),
mem_total: Math.ceil(req.body.mem.total)
};
this.streamers.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 ${ streamerId } Not Found`);
return;
}
this.info(`${ tag }ID ${ streamerId } Updated`);
res.sendStatus(200);
});
}
}
module.exports = StreamerHandler;
//# sourceMappingURL=streamer-handler.js.map