Extract out Robot param validation into new file

This commit is contained in:
Andrew Stewart 2015-06-10 17:17:11 -07:00
parent ad2db2d459
commit 4238385be4
2 changed files with 49 additions and 34 deletions

View File

@ -14,6 +14,8 @@ var initializer = require("./initializer"),
Config = require("./config"),
_ = require("./utils/helpers");
var validator = require("./validator");
var Async = require("async"),
EventEmitter = require("events").EventEmitter;
@ -36,6 +38,8 @@ var Robot = module.exports = function Robot(opts) {
opts = opts || {};
validator.validate(opts);
var methods = [
"toString",
"halt",
@ -53,9 +57,6 @@ var Robot = module.exports = function Robot(opts) {
}, this);
this.initRobot(opts);
this.checkForBadSyntax(opts);
this.initConnections(opts);
this.initDevices(opts);
@ -166,37 +167,6 @@ Robot.prototype.initRobot = function(opts) {
}
};
/**
* Checks provided options object for invalid Robot details
*
* @param {Object} opts options object to check for errors
* @return {void}
*/
Robot.prototype.checkForBadSyntax = function(opts) {
var self = this;
var RobotDSLError = new Error("Unable to start robot due to a syntax error");
RobotDSLError.name = "RobotDSLError";
function has(prop) { return opts[prop] != null; }
function checkForSingleObjectSyntax(type) {
var plural = type + "s";
if (has(type) && !has(plural)) {
[
"The single-object '" + type + "' syntax for robots is not valid.",
"Instead, use the multiple-value '" + plural + "' key syntax.",
"Details: http://cylonjs.com/documentation/guides/working-with-robots/"
].forEach(function(str) { self.log("fatal", str); });
throw RobotDSLError;
}
}
["connection", "device"].forEach(checkForSingleObjectSyntax);
};
/**
* Initializes a Robot's connections
*

45
lib/validator.js Normal file
View File

@ -0,0 +1,45 @@
"use strict";
// validates an Object containing Robot parameters
var Logger = require("./logger");
function hasProp(object, prop) {
return object.hasOwnProperty(prop);
}
function die() {
var RobotDSLError = new Error("Unable to start robot due to a syntax error");
RobotDSLError.name = "RobotDSLError";
throw RobotDSLError;
}
function log(messages) {
messages = [].concat(messages);
messages.map(function(msg) { Logger.fatal(msg); });
}
var check = {};
check.singleObjectSyntax = function(opts, key) {
var single = hasProp(opts, key),
plural = hasProp(opts, key + "s");
if (single && !plural) {
log([
"The single-object '" + key + "' syntax for robots is not valid.",
"Instead, use the multiple-value '" + key + "s' key syntax.",
"Details: http://cylonjs.com/documentation/guides/working-with-robots/"
]);
die();
}
};
module.exports.validate = function validate(opts) {
opts = opts || {};
["connection", "device"].map(function(type) {
check.singleObjectSyntax(opts, type);
});
};