Move API command param parsing to middleware
This commit is contained in:
parent
0e019f1151
commit
9b352feeae
20
lib/api.js
20
lib/api.js
|
@ -43,6 +43,26 @@ var API = module.exports = function API(opts) {
|
|||
return next();
|
||||
});
|
||||
|
||||
// extracts command params from request
|
||||
this.server.use(function(req, res, next) {
|
||||
var method = req.method.toLowerCase(),
|
||||
container = {};
|
||||
|
||||
req.commandParams = [];
|
||||
|
||||
if (method === 'get' || Object.keys(req.query).length > 0) {
|
||||
container = req.query;
|
||||
} else if (typeof(req.body) === 'object') {
|
||||
container = req.body;
|
||||
}
|
||||
|
||||
for (var p in container) {
|
||||
req.commandParams.push(container[p]);
|
||||
};
|
||||
|
||||
return next();
|
||||
});
|
||||
|
||||
// load route definitions
|
||||
this.server.use('/', require('./api/routes'))
|
||||
};
|
||||
|
|
|
@ -10,26 +10,6 @@ var Cylon = require('../cylon');
|
|||
|
||||
var router = module.exports = require('express').Router();
|
||||
|
||||
// Parses req to extract params to be used for commands.
|
||||
//
|
||||
// Returns an array of params
|
||||
var parseCommandParams = function(req) {
|
||||
var param_container = {},
|
||||
params = [];
|
||||
|
||||
if (req.method === 'GET' || Object.keys(req.query).length > 0) {
|
||||
param_container = req.query;
|
||||
} else if (typeof req.body === 'object') {
|
||||
param_container = req.body;
|
||||
}
|
||||
|
||||
for (var p in param_container) {
|
||||
params.push(param_container[p]);
|
||||
}
|
||||
|
||||
return params;
|
||||
};
|
||||
|
||||
router.get("/robots", function(req, res) {
|
||||
var data = [];
|
||||
|
||||
|
@ -54,12 +34,10 @@ router.get("/robots/:robot/commands", function(req, res) {
|
|||
});
|
||||
|
||||
router.all("/robots/:robot/commands/:command", function(req, res) {
|
||||
var params = parseCommandParams(req);
|
||||
|
||||
Cylon.findRobot(req.params.robot, function(err, robot) {
|
||||
if (err) { return res.json(err); }
|
||||
|
||||
var result = robot[req.params.command].apply(robot, params);
|
||||
var result = robot[req.params.command].apply(robot, req.commandParams);
|
||||
res.json({ result: result });
|
||||
});
|
||||
});
|
||||
|
@ -119,12 +97,10 @@ router.all("/robots/:robot/devices/:device/commands/:command", function(req, res
|
|||
device = req.params.device,
|
||||
command = req.params.command;
|
||||
|
||||
var params = parseCommandParams(req);
|
||||
|
||||
Cylon.findRobotDevice(robot, device, function(err, device) {
|
||||
if (err) { return res.json(err); }
|
||||
|
||||
var result = device[command].apply(device, params);
|
||||
var result = device[command].apply(device, req.commandParams);
|
||||
res.json({ result: result });
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue