From 5d2fc21fab7ea1e79a543dd72201e1afa975c442 Mon Sep 17 00:00:00 2001 From: Loren West Date: Thu, 25 Dec 2014 22:08:04 -0800 Subject: [PATCH] Support asynchronous commands --- lib/api/routes.js | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) 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 }); + } +};