diff --git a/lib/api/routes.js b/lib/api/routes.js index f2bdc31..864a2b5 100644 --- a/lib/api/routes.js +++ b/lib/api/routes.js @@ -60,9 +60,8 @@ router.get("/commands", function(req, res) { }); router.post("/commands/:command", function(req, res) { - var command = req.params.command; - var result = Cylon.commands[command].apply(Cylon, req.commandParams); - res.json({ result: result }); + var command = Cylon.commands[req.params.command]; + router.runCommand(req, res, Cylon, command); }); router.get("/robots", function(req, res) { @@ -79,8 +78,7 @@ router.get("/robots/:robot/commands", load, function(req, res) { router.all("/robots/:robot/commands/:command", load, function(req, res) { var command = req.robot.commands[req.params.command]; - var result = command.apply(req.robot, req.commandParams); - res.json({ result: result }); + router.runCommand(req, res, req.robot, command); }); router.get("/robots/:robot/devices", load, function(req, res) { @@ -117,8 +115,7 @@ router.get("/robots/:robot/devices/:device/commands", load, function(req, res) { router.all("/robots/:robot/devices/:device/commands/:command", load, function(req, res) { var command = req.device.commands[req.params.command]; - var result = command.apply(req.device, req.commandParams); - res.json({ result: result }); + router.runCommand(req, res, req.device, command); }); router.get("/robots/:robot/connections", load, function(req, res) { @@ -128,3 +125,17 @@ router.get("/robots/:robot/connections", load, function(req, res) { router.get("/robots/:robot/connections/:connection", load, function(req, res) { res.json({ connection: req.connection }); }); + +// Run an MCP, Robot, or Device command. Process the results immediately, +// or asynchronously if the result is a Promise. +router.runCommand = function(req, res, my, command) { + var result = command.apply(my, req.commandParams); + if (typeof result.then === 'function') { + result + .then(function(result) {return res.json({result: result})}) + .catch(function(err) {return res.status(500).json({error: err})}); + } + else { + res.json({ result: result }); + } +};