const config = require('../config.json'); const logger = require('./logger.js'); const api = require('./api.js') const constants = require('./constants.js'); const modep = require('./modep.js'); const http = require('http'); var server; function start() { return new Promise(function (resolve, reject) { if (!server) { server = http.createServer(); } server.listen(config.server.port, config.server.listen).on('listening', function () { logger.debug('server listening on ' + config.server.listen + ':' + config.server.port + '...'); handleRequests(); }); }); } function handleRequests() { server.on('request', function (request, response) { logger.request(request); if (request.url.endsWith('/')) { request.url = request.url.substring(0, request.url.length - 1); } var endpoint = api.getEndpoints().get(request.url); if (!endpoint) { var msg = 'endpoint \'' + request.url + '\' not defined'; response.writeHead(501); response.end(msg); logger.debug(msg); return; } endpoint = endpoint[request.method]; if (endpoint == undefined || endpoint.method == undefined) { var msg = 'error: endpoint \'' + request.url + '\' does not have any handlers for ' + request.method + ' requests'; response.writeHead(405); response.end(msg); logger.debug(msg); return; } getRequestParams(request) .then(function (params) { return endpoint.method(endpoint.id, params); }) .then(function (result) { response.writeHead(200); try { response.end(JSON.stringify(result)); } catch (err) { response.end(result); } }) .catch(function (err, code) { logger.error(err); if (code == undefined) { code = 500; } response.writeHead(500); response.end(err); }); }); } function getRequestParams(request) { return new Promise(function (resolve, reject) { var params = ""; request.on("data", function (data) { params += data; }); request.on("end", function () { if (params == undefined || params.length == 0) { return resolve(); } return resolve(new URLSearchParams(params)); }); }); } function handlePOSTPedals(request) { return new Promise(function (resolve, reject) { getRequestParams(request) .then(function (params) { var pedalId = request.url.substring(request.url.lastIndexOf('/') + 1); var controlId = params.get('id'); if (controlId == undefined) { reject('error: could not handle POST - missing parameter \'id\'', 400) } var value = params.get('value'); if (value == undefined) { reject('error: could not handle POST - missing parameter \'value\'', 400) } modep.getPedalControlById(pedalId, controlId) .then(function (control) { modep.sendValueToControl(value, control); }) .then(resolve) .catch(reject); }) .catch(reject); }); } function handlePOSTPedalboards(request) { return new Promise(function (resolve, reject) { modep.setPedalboardById(request.url.substring(request.url.lastIndexOf('/') + 1)) .then(resolve) .catch(reject); }); } module.exports = { start }