Skip to content
Browse files

[api] Improved argument parsing for functions bound with Resource.method

  • Loading branch information...
1 parent 3799bbd commit d5b53da809d69fbd00007ac823b31f0c28b5344e @Marak Marak committed
Showing with 49 additions and 7 deletions.
  1. +49 −7 lib/resourceful/resource.js
View
56 lib/resourceful/resource.js
@@ -723,16 +723,52 @@ Resource.object = function (name, schema) {
};
Resource.method = function (name, fn, schema) {
+ var that = this;
+
if(typeof this[name] !== 'undefined') {
throw new Error(name + ' is a reserved word on the Resource definition')
}
if (typeof schema === 'object') {
this[name] = function(){
var args = utile.args(arguments);
- if(args.length === 0) {
- args[0] = {};
- }
- var valid = validator.validate(args[0], schema);
+ var payload = {};
+
+
+ //
+ // Compare parsed arguments to expected schema
+ //
+ args.forEach(function(arg, i){
+ //
+ // For every argument, try to match it to a schema value
+ // The order of arguments is expected to match the order of schema property declaration
+ //
+ Object.keys(schema.properties).forEach(function(prop, j){
+ if(j === i) {
+ payload[prop] = arg;
+ }
+ });
+ });
+
+ //
+ // TODO: better default settings using new(that)(payload) instance
+ //
+ Object.keys(schema.properties).forEach(function(prop, j){
+ if(typeof payload[prop] === "undefined" && typeof schema.properties[prop].default !== 'undefined') {
+ payload[prop] = schema.properties[prop].default;
+ }
+ });
+
+ // turn payload back into args
+ var _args = [];
+ Object.keys(payload).forEach(function(val){
+ _args.push(payload[val]); // ignore the key, assume order of arguments is 1:1 to schema property declarations
+ });
+
+ //
+ // TODO: if only argument is callback and its not provided,
+ // make noop callback so the method doesn't crash
+ //
+ var valid = validator.validate(payload, schema);
if(!valid.valid) {
if(typeof args.cb === 'function') {
args.cb(valid);
@@ -740,12 +776,18 @@ Resource.method = function (name, fn, schema) {
throw new Error(JSON.stringify(valid.errors)); // TODO: better errors
}
} else {
- return fn.apply(this, arguments);
+ //
+ // If there is a callback, push it back into the arguments
+ //
+ if(typeof args.cb === "function") {
+ _args.push(args.cb);
+ }
+ return fn.apply(this, _args);
}
};
- } else {
- this[name] = fn;
}
+
+ this[name] = fn;
this[name].type = "method";
this[name].schema = schema;
if(typeof this.methods === "undefined") {

0 comments on commit d5b53da

Please sign in to comment.
Something went wrong with that request. Please try again.