domotz-remote-pawn
Version:
Domotz Agent
68 lines (63 loc) • 2.32 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2016 Domotz Ltd
*
* Domotz Agent is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Domotz Agent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>.
**/
/**
* Created by Massimiliano Cuzzoli <mcuzzoli@domotz.com> on 27/08/15.
*
*/
const MODULE_NAME = 'SOCKET_HANDLER';
function handleAction(action) {
console.debug('%s - Received action: %s', MODULE_NAME, action);
switch (action) {
case 'listener_status_check':
console.info('%s - Check Listener Status. TODO: Diagnostic Module', MODULE_NAME);
break;
default:
throw new Error('Unsupported action ' + action + ' requested on socket');
}
}
function parseBody(body) {
var command = JSON.parse(body);
if (!command.action) {
throw new Error('Invalid request body = ' + body);
}
return command;
}
module.exports.handleRequest = function (request, response) {
var body = '';
if (request.method !== 'POST') {
console.warn('%s - Received unknown method: %s', MODULE_NAME, request.method);
response.writeHead(400);
response.end();
} else {
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
try {
var command = parseBody(body);
handleAction(command.action);
console.info('%s - External request handled properly. Action: %s', MODULE_NAME, command.action);
response.writeHead(200);
response.end();
} catch (err) {
console.warn('%s - Bad request: %s', MODULE_NAME, err.message);
response.writeHead(400);
response.end();
}
});
}
};