APIHandler.js: use promises

pull/3559/head
Ray Bellis 2019-01-22 13:30:28 +00:00
parent ec5baa2ab3
commit c4f1f83747
1 changed files with 22 additions and 28 deletions

View File

@ -150,7 +150,7 @@ exports.version = version;
* @req express request object
* @res express response object
*/
exports.handle = function(apiVersion, functionName, fields, req, res)
exports.handle = async function(apiVersion, functionName, fields, req, res)
{
//check if this is a valid apiversion
var isKnownApiVersion = false;
@ -194,41 +194,38 @@ exports.handle = function(apiVersion, functionName, fields, req, res)
return;
}
try {
// sanitize any padIDs before continuing
if (fields["padID"]) {
padManager.sanitizePadId(fields["padID"], function(padId) {
fields["padID"] = padId;
callAPI(apiVersion, functionName, fields, req, res);
});
fields["padID"] = await padManager.sanitizePadId(fields["padID"]);
} else if (fields["padName"]) {
padManager.sanitizePadId(fields["padName"], function(padId) {
fields["padName"] = padId;
callAPI(apiVersion, functionName, fields, req, res);
});
} else {
callAPI(apiVersion, functionName, fields, req, res);
fields["padName"] = await padManager.sanitizePadId(fields["padName"]);
}
await callAPI(apiVersion, functionName, fields, req, res);
} catch (e) {
ERR(e);
}
}
// calls the api function
function callAPI(apiVersion, functionName, fields, req, res)
async function callAPI(apiVersion, functionName, fields, req, res)
{
// put the function parameters in an array
var functionParams = version[apiVersion][functionName].map(function (field) {
return fields[field]
});
// add a callback function to handle the response
functionParams.push(function(err, data) {
if (err == null) {
// no error happened, everything is fine
try {
// call the api function
let data = await api[functionName].apply(this, functionParams);
if (!data) {
data = null;
}
res.send({code: 0, message: "ok", data: data});
} else if (err.name == "apierror") {
} catch (err) {
if (err.name == "apierror") {
// parameters were wrong and the api stopped execution, pass the error
res.send({code: 1, message: err.message, data: null});
@ -236,10 +233,7 @@ function callAPI(apiVersion, functionName, fields, req, res)
// an unknown error happened
res.send({code: 2, message: "internal error", data: null});
ERR(err);
throw err;
}
}
});
// call the api function
api[functionName].apply(this, functionParams);
}