Skip to content

Instantly share code, notes, and snippets.

@stevegraham
Last active December 30, 2015 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevegraham/7815774 to your computer and use it in GitHub Desktop.
Save stevegraham/7815774 to your computer and use it in GitHub Desktop.
Restafarian "code-on-demand" example used to inform client what a valid resource is, including non-authorative property validations.
Function.prototype.curry = function() {
var fn = this;
var slice = Array.prototype.slice;
var args = slice.call(arguments);
return function() {
return fn.apply(this, args.concat(slice.call(arguments)));
}
}
var Resource = {};
Resource.name = "User";
Resource.flags = {
create: 1,
update: 2,
save: 1 | 2,
}
Resource.validators = {
base: function(opts, fn, errors, key, on) {
if(on & (opts.on || Resource.flags.save)) {
key = fn.call(this, key, opts);
if(key) {
errors[key] = errors[key] || [];
errors[key].push(opts.message);
}
};
},
presence: function(opts) {
return this.base.curry(opts, function(key, _) {
if(!this[key]) return key;
});
},
length: function(opts) {
return this.base.curry(opts, function(key, opts) {
var string = this[key] || "";
var l = opts.tokenizer(string).length;
var min = opts.minimum;
var max = opts.maximum;
if(l < min || l > max) return key;
});
},
acceptance: function(opts) {
return this.presence(opts);
},
inclusion: function(opts) {
return this.base.curry(opts, function(key, opts) {
if(opts['in'].indexOf(this[key]) < 0) return key;
});
},
confirmation: function(opts) {
return this.base.curry(opts,function(key, _) {
if(this[key] !== this[key + '_confirmation']) {
return key + '_confirmation';
}
});
}
}
Resource.validate = function(representation, on) {
var errors = {};
for(var property in this.properties) {
if(this.properties.hasOwnProperty(property)) {
this.properties[property].validators.forEach(function(validator) {
validator.call(representation, errors, property, on);
})
}
};
return errors;
}
Resource.properties = {
full_name: {
localized_name: "Full name",
type: "text",
validators: [Resource.validators.presence({'message': 'must be present'}),
Resource.validators.length({'message': "is too short", "minimum": 2, "tokenizer": function(string) { return string.split(/\W+/); }}),
Resource.validators.inclusion({'message': 'must be one of the flower pot men', 'in': ['Bill', 'Bob']})]
}
}
// var errors = Resource.validate({ "full_name" : "Bob" }, Resource.flags.save);
//
// { full_name: ["is too short", "must be one of the flower pot men"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment