JavaScript argument validation - javascript

I am writing an Angular app coming from a PHP background. I wanted to know if there are any good assert/validation libraries I can use to help me validation the arguments passed in to my models e.g. Validate.isNumber(data.id) and automatically throw an appropriate exception on failure
app.factory('Something', ['moment', function(moment){
function Something(data) {
// validate data has required properties and they are of the expected type!!!
this.id = data.id;
this.title = data.title;
this.description = data.description;
}
Something.prototype.getId = function () {
return this.id;
};
Something.prototype.getTitle = function () {
return this.title;
};
Something.prototype.getDescription = function () {
return this.description;
};
return Something;
}]);

I personally use this JSON-Validator tv4:
https://github.com/geraintluff/tv4
It relies on a schema you provide to tell it how your passed arguments(JSON-structure) have to be formed and what kind of types are allowed.
And here you find all validation-options it supports:
http://json-schema.org/latest/json-schema-validation.html
Here you find a practical example

Related

set object properties when every() on array return false

I've finally used another logic (using "let" with break), but I would be happy to have (if it's feasible) another solution:
I've built a validation service which iterate over (injected) list of objects that contains regex expressions and relevant message (and input element) for each expression. I'm using every() method to iterate over the regex expressions. The service knows to return true or false when testing the regex.
The problem is that except for getting true\false I would like the consumer of the service to get the relevant message and the input element. So, in the service class I have 2 properties (lets call them "message" and "element") and I thought to set them accordingly. But, when I'm in the context of the every - the "this" refer to the context and not to the class. I thought of sending those 2 properties as parameters to the every method. Is that the best practice?
See relevant code:
export class userValidation
{
constructor() {
this.validationMessage = '';
this.validationElement = '';
//}
validateByExpression(elementValidator, valueToValidate, functionToExec) {
var validationMessage = this.validationMessage;//Trying to get reference - no go
if (elementValidator.regex.test(valueToValidate) == false)
{
//This is the part where I need to store\return the relevant message
validationMessage = elementValidator.message; // fails
return false;
}
else
{
return true;
}
}
validate(validationElement, elementName, valueToValidate)
{
var regexExpList = new Array(validationElement);
var getValidationMessage = this.getValidationMessage;
var validateByExpression = this.validateByExpression;
var validationMessage = this.validationMessage;
return regexExpList.every(function(regexExp) { return
getValidationMessage(validateByExpression, regexExp[elementName],
valueToValidate, validationMessage) });
}
}

Angular services with default values for non-existing attributes

Working on an Ionic application that performs both in Android and Windows.
There are services, such as Ionic's $ionicLoading, which we override functionality in order to work properly in windows:
angular.factory('$ionicLoading', function(){
return {
show: function (){...} // custom implementation
hide: function (){...} // custom implementation
}
});
But there are other services which we have to override only to not break the app.
In this cases it would be really useful to provide a service that won't do anything. For example:
angular.factory('$ionicExampleService', function(){
return {
*foo*: angular.noop // for operations
*bar*: promise // returns promise
}
});
Note: I know that a better way of doing this would be with a service that chooses between Ionic's implementation or a made one, but this is just for the sake of learning.
The ideal would be going even further, it would be magnificent to be able to return something even more bulletproof. Something like a generic flexible services:
angular.factory('$ionicPopup', function(){
return /*magic*/;
});
$ionicPopup.show({...}) // show was not defined
.then(foo); // won't break and will execute foo()
It is possible?
From what I understood you need to override implementation of existing services. You can do that with an angular service decorator.
A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.
For more information you can check angular documentation. One simple example would be:
app.factory('someService', function () {
return {
method1: function () { return '1'; }
method2: function () { return '2'; }
};
});
app.decorator('someService', function ($delegate) {
// NOTE: $delegate is the original service
// override method2
$delegate.method2 = function () { return '^2'; };
// add new method
$delegate.method3 = function () { return '3'; };
return $delegate;
});
// usage
app.controller('SomeController', function(someService) {
console.log(someService.method1());
console.log(someService.method2());
console.log(someService.method3());
});
EDIT: Question - How to override every method in the service?
var dummyMethod = angular.noop;
for(var prop in $delegate) {
if (angular.isFunction($delegate[prop])) {
$delegate[prop] = dummyMethod;
}
}
I hope that this helps you.
Using an evaluation for each assignment based on an object property, similar to this:
myVar = myObj.myPropVar === undefined ? "default replacement" : myObj.myPropVar;
Basically you're using a check for if the property has been defined, substituting a default value if it hasn't, and assigning it if it has.
Alternatively, you can use a modified version of the global function in Sunny's linkback to define defaults for all those properties you might assume to be undefined at specific points in your code.
function getProperty(o, prop) {
if (o[prop] !== undefined) return o[prop];
else if(prop == "foo") return "default value for foo";
else if(prop == "bar") return "default value for bar";
/* etc */
else return "default for missing prop";
}
Hope that helps,
C§
use var a = {}; to declare new variable.

Mocha tests mocking function

I'm testing backbone view, that have function:
attachSelect: function(id, route) {
console.log(id);
console.log(route);
this.$(id).select2({
ajax: {
url: route,
dataType: 'json',
results: function(data) {
var results = _.map(data, function(item) {
return {
id: item.id,
text: item.title
};
});
return {
results: results
};
},
cache: true
}
});
}
I need to rewrite (mock) this fuction that, the looks like:
attachSelect: function(id, route) {
console.log(id);
console.log(route);
}
How to do that ?
The simplest way to mock a function is to replace the property at runtime.
You can provide your own monitoring function (commonly called a spy), although this is not the most elegant. That would look like:
var called = false;
var testee = new ViewUnderTest();
var originalAttach = testee.attachSelect; // cache a reference to the original
testee.attachSelect = function () {
called = true;
var args = [].concat(arguments); // get an array of arguments
return originalAttach.apply(testee, args);
};
// Perform your test
expect(called).to.be.true;
If you have a test assertion library like chai, you can use the spies plugin and reduce that to:
var testee = new ViewUnderTest();
var spy = chai.spy(testee.attachSelect);
testee.attachSelect = spy;
// Perform your test
expect(spy).to.have.been.called();
Using a spy library will provide some useful features, such as monitoring the number of calls and their arguments to verify low-level behavior. If you're using Chai or Jasmine, I would highly suggest taking advantage of the corresponding support for spies.

Custom JQuery Plugin Method error

I've been working on writing a custom jquery plugin for one of my web applications but I've been running into a strange error, I think it's due to my unfamiliarity with object-oriented programming.
The bug that I've been running into comes when I try to run the $(".list-group").updateList('template', 'some template') twice, the first time it works just fine, but the second time I run the same command, I get an object is not a function error. Here's the plugin code:
(function($){
defaultOptions = {
defaultId: 'selective_update_',
listSelector: 'li'
};
function UpdateList(item, options) {
this.options = $.extend(defaultOptions, options);
this.item = $(item);
this.init();
console.log(this.options);
}
UpdateList.prototype = {
init: function() {
console.log('initiation');
},
template: function(template) {
// this line is where the errors come
this.template = template;
},
update: function(newArray) {
//update code is here
// I can run this multiple times in a row without it breaking
}
}
// jQuery plugin interface
$.fn.updateList = function(opt) {
// slice arguments to leave only arguments after function name
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var item = $(this), instance = item.data('UpdateList');
if(!instance) {
// create plugin instance and save it in data
item.data('UpdateList', new UpdateList(this, opt));
} else {
// if instance already created call method
if(typeof opt === 'string') {
instance[opt](args);
}
}
});
}
}(jQuery));
One thing I did notice when I went to access this.template - It was in an array so I had to call this.template[0] to get the string...I don't know why it's doing that, but I suspect it has to do with the error I'm getting. Maybe it can assign the string the first time, but not the next? Any help would be appreciated!
Thanks :)
this.template = template
Is in fact your problem, as you are overwriting the function that is set on the instance. You end up overwriting it to your args array as you pass that as your argument to the initial template function. It basically will do this:
this.template = ["some template"];
Thus the next time instance[opt](args) runs it will try to execute that array as if it were a function and hence get the not a function error.
JSFiddle

Add methods to a collection returned from an angular resource query

I have a resource that returns an array from a query, like so:
.factory('Books', function($resource){
var Books = $resource('/authors/:authorId/books');
return Books;
})
Is it possible to add prototype methods to the array returned from this query? (Note, not to array.prototype).
For example, I'd like to add methods such as hasBookWithTitle(title) to the collection.
The suggestion from ricick is a good one, but if you want to actually have a method on the array that returns, you will have a harder time doing that. Basically what you need to do is create a bit of a wrapper around $resource and its instances. The problem you run into is this line of code from angular-resource.js:
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
This is where the return value from $resource is set up. What happens is "value" is populated and returned while the ajax request is being executed. When the ajax request is completed, the value is returned into "value" above, but by reference (using the angular.copy() method). Each element of the array (for a method like query()) will be an instance of the resource you are operating on.
So a way you could extend this functionality would be something like this (non-tested code, so will probably not work without some adjustments):
var myModule = angular.module('myModule', ['ngResource']);
myModule.factory('Book', function($resource) {
var service = $resource('/authors/:authorId/books'),
origQuery = service.prototype.$query;
service.prototype.$query = function (a1, a2, a3) {
var returnData = origQuery.call(this, a1, a2, a3);
returnData.myCustomMethod = function () {
// Create your custom method here...
return returnData;
}
}
return service;
});
Again, you will have to mess with it a bit, but that's the basic idea.
This is probably a good case for creating a custom service extending resource, and adding utility methods to it, rather than adding methods to the returned values from the default resource service.
var myModule = angular.module('myModule', []);
myModule.factory('Book', function() {
var service = $resource('/authors/:authorId/books');
service.hasBookWithTitle = function(books, title){
//blah blah return true false etc.
}
return service;
});
then
books = Book.list(function(){
//check in the on complete method
var hasBook = Book.hasBookWithTitle(books, 'someTitle');
})
Looking at the code in angular-resource.js (at least for the 1.0.x series) it doesn't appear that you can add in a callback for any sort of default behavior (and this seems like the correct design to me).
If you're just using the value in a single controller, you can pass in a callback whenever you invoke query on the resource:
var books = Book.query(function(data) {
data.hasBookWithTitle = function (title) { ... };
]);
Alternatively, you can create a service which decorates the Books resource, forwards all of the calls to get/query/save/etc., and decorates the array with your method. Example plunk here: http://plnkr.co/edit/NJkPcsuraxesyhxlJ8lg
app.factory("Books",
function ($resource) {
var self = this;
var resource = $resource("sample.json");
return {
get: function(id) { return resource.get(id); },
// implement whatever else you need, save, delete etc.
query: function() {
return resource.query(
function(data) { // success callback
data.hasBookWithTitle = function(title) {
for (var i = 0; i < data.length; i++) {
if (title === data[i].title) {
return true;
}
}
return false;
};
},
function(data, response) { /* optional error callback */}
);
}
};
}
);
Thirdly, and I think this is better but it depends on your requirements, you can just take the functional approach and put the hasBookWithTitle function on your controller, or if the logic needs to be shared, in a utilities service.

Categories

Resources