divhide-core
Javascript codebase to use on the Browser, NodeJS and other javascript platforms. This provides a set of utilities that you can use everywhere.
The intent of this library is to expose some building blocks that you can use when building a library, a mobile application, a web page, a web server, a command line utility...
Please note that all examples are integrated on the CI build and that's the reason why you'll see expect
statements.
Install
Node.js
npm install divhide
var Divhide = require("divhide");
...
Bower
bower install divhide
<script type="text/javascript" src="//bower_components/divhide/dist/divhide.js"></script>
<script type="text/javascript">
var fn = Divhide.Safe.function();
...
</script>
Titanium
Download dist/divhide.js from github and use it as a library.
e.g.
var Divhide = require("/vendor/divhide");
API
I18N
The Internationalization package. This package provides you with some utilities that will help you
on your internationalization tasks.
There's no intention for this library to contain translations for other languages.
I18NString
The I18NString is a String representation that can be translated. This string can be a plain String or
a lodash template.
This implementation creates a clear separation between the translation mechanism and it's internal logic. This package is used across the library in order to provide I18N out of the box!
Constructor
new I18N.String(message, data?, translations?)
Creates a String instance with the given message, associated data, and an object which contain the translation.
Methods
Gets the string representation of the error. If translations object is provided the message Error message will try to be translated.
Example
var I18NString = Divhide.I18N.String;
var Portuguese = {
"hello <%= username %>": "olá <%= username %>"
};
var message = new I18NString("hello <%= username %>", { username: "oscar" });
var en = message.toString();
expect(en)
.toBe("hello oscar");
var en = message.toString(Portuguese);
expect(en)
.toBe("olá oscar");
Exception
The Exception package provides some utilities created in order to normalize the Error handling.
All the Exceptions classes inherit from Error. Also, these classes are using the I18N
package.
Exception
The Exception class inherits from Error. This class is integrated with I18N package.
Constructor
new Exception.Exception(message, data?)
Creates an instance of an exception with the given message and data.
Methods
Gets the string representation of the error.
Gets the string representation of the I18NString. You can provide a translation object.
Example
var Exception = Divhide.Exception.Exception;
var Portuguese = {
"The maximum value allowed is <%= value %>.": "Valor máximo é <%= value %>."
};
var error = new Exception(
"The maximum value allowed is <%= value %>.",
{ value: 10 });
expect(error instanceof Error)
.equals(true);
expect(error.toString())
.equals("The maximum value allowed is 10.");
expect(error.toString(Portuguese))
.equals("Valor máximo é 10.");
ExceptionList
This allows you to create an Exception that contains inner exceptions.
The ExceptionList is also an instance of Error and compatible with the I18N package.
Constructor
new Exception.ExceptionList()
Methods
Gets the string representation of the ExceptionList.
Gets the list of inner Error.
Gets length of the ExceptionList
Clear the ExceptionList
Push an Error instance to the ExceptionList
Merge the given ExceptionList into the instance
Gets the string representation of the I18NString. You can provide a translation object.
Example
var Exception = Divhide.Exception.Exception,
ExceptionList = Divhide.Exception.ExceptionList;
var errors = new ExceptionList();
expect(errors instanceof Error)
.toEqual(true);
errors.push( new Exception("Error1") );
errors.push( new Exception("Error2") );
errors.push( new Exception("Error3") );
expect(errors.length)
.toEqual(3);
expect(errors.items[0].toString())
.toEqual("Error1");
expect(errors.toString({ "Error1": "Error 1", "Error2": "Error 2", "Error3": "Error 3" }))
.toEqual("Error 1, Error 2, Error 3");
Assert
The Assert facility provides an assertion expression builder with some pre-built functions.
Methods
Set the expected value to be defined
Set the expected value to be a string
Set the expected value to be an array
Set the expected value to be an object
Set the expected value to be a number
Set the expected value to have a specified maximum. In the case of String or Array the context will be the value length. In the case of an object will be the number of keys
Set the expected value to have a specified minimum. In the case of String or Array the context will be the value length. In the case of an object will be the number of keys
Set the expected value to pass the regex
Test if the given value is valid within the current assertion
Return the given value if valid; otherwise will throw an Exception
Example
var Assert = Divhide.Assert;
var isValid = Assert.required()
.string()
.regex("^M")
.max(10)
.min(5)
.isValid("Mary");
expect(isValid)
.toBe(false);
var obj = Assert.required()
.array()
.max(5)
.assert([1, 2, 4, 5]);
expect(obj)
.equals([1, 2, 4, 5]);
var fn = function(){
Assert.required()
.array()
.max(1)
.assert(["first", "second"]);
};
expect(fn)
.toThrow();
Assertion
Assertion facility provides a way to build custom Asserts. You can create your own assertion functions
and integrate them with the Assert facility.
Constructor
Creates a custom assertion instance that contains the given methods plus the default methods (see Assert).
var Assertion = Divhide.Assertion;
var Assert = new Assertion({
startsWith: function(val, str){
if(val.indexOf(str) !== 0){
throw new Error("Does not starts with " + str);
}
}
});
var isValid = Assert
.required()
.string()
.startsWith("Mary")
.isValid("Mary and Peter");
expect(isValid)
.toBe(true)
var value = Assert
.required()
.string()
.startsWith("Mary")
.assert("Mary and Peter");
expect(value)
.equals("Mary and Peter");
Chain
Chain facility provides an API to create chainable functions. Each Chain is created by a list of chainable functions, a list of evaluation
function and some options.
Constructor
new Chain(chainableFns, evaluationFns, options)
Creates a Chain instance that allows you to execute chainable methods (chainableFns). The chain is only executed
when an evaluation method (evaluationFns) is called.
* chainableFns
* evaluationFns
* options - { pipe: Boolean, type: Function, argument: *, scope: Object }
.
var Chain = Divhide.Chain;
var Maths = new Chain(
{
sum: function(i,j){
return i + j;
},
sub: function(i, j){
return i - j;
}
},
{
calculate: function(result, err){
return result;
}
},
{
pipe: true
});
var value = Maths.sum(5)
.sub(3)
.sum(10)
.calculate(0);
expect(value)
.toBe(12);
Schema
The Schema facility provide an easy way to write validation rules. Using a chainable API you can
compile and/or evaluate the rules.
Methods
.any()
Set the expected type as any object.
.string()
Set the expected type as a string
.number()
Set the expected type as a number
.object(value)
Set the expected type as an object. The value is an object with rules.
.array(value)
Set the expected type as an object. The value is an array with rules.
.required()
Set as required.
.optional()
Set as optional
.default(value)
Set the default value. This is used when the schema its required and the provided value is null.
.repeatable()
Set the type as repeatable. This repeats the schema through the structure (array only!).
.min(value)
Set the min value expected. If in number context the value is used. If in string context the length is used.
If in array context the length is used. If in object context the number of keys is used.
.max(value)
Set the max value expected. If in number context the value is used. If in string context the length is used.
If in array context the length is used. If in object context the number of keys is used.
.regex(value)
Sets a regexp condition ( only use on string context! )
.compile()
Compiles the schema. If you are using the same Schema multiple time you can compile it for performance reasons.
This avoid compiling the Schema before every usage.
.value(value)
Test the schema returning the normalized value if valid. Throws an Error if invalid.
.isValid(value)
Test the schema return if its valid or not.
.errors(value)
Test the schema returning an Array with the errors
.serialize()
Gets the serialized schema representation.
.deserialize(value)
Gets the Schema from the given value.
Example overview
var Schema = Divhide.Schema;
var schema = Schema.object({
data: Schema.array([ "" ]).repeatable().max(10),
"/.*/": Schema.string().optional()
}).required();
var value = schema.value(
{
data: [ 1, 2, 3, 4, 5 , 6],
timestamp: "1404373579473"
});
expect(value).equals(
{
data: [ '1', '2', '3', '4', '5' , '6'],
timestamp: "1404373579473"
});
Example String Schema
var Schema = Divhide.Schema;
var serialized =
Schema.object({
"name" : "",
"friends" : Schema.array([
{
name: ""
}
]).optional(),
})
.required()
.serialize();
var schema = Schema.deserialize(serialized);
var value = schema.value({
id: 1,
name: "Oscar",
friends: [{ name: "Solange" }]
});
expect(value).equals({
name: "Oscar",
friends: [{ name: "Solange" }]
});
Time to see some code! Some usage examples are described below.
Example Number Schema
var Schema = Divhide.Schema;
var schema = Schema.number()
.optional()
.min(3)
.max(5)
.compile();
var value = schema.value(3);
expect(value).toBe(3)
var value = schema.value();
expect(value).equals(null);
expect(
function(){
schema.value(0);
})
.toThrow(
new Error("The minimum value allowed is 3.")
);
expect(
function(){
schema.value(10);
})
.toThrow(
new Error("The maximum value allowed is 5.")
);
var isValid = schema.isValid();
expect(isValid).toBe(true);
isValid = schema.isValid(3);
expect(isValid).toBe(true);
isValid = schema.isValid(10);
expect(isValid).toBe(false);
Example Schema (de)serialization
var Schema = Divhide.Schema;
var schema = Schema.string()
.required()
.min(3)
.max(5);
var value = schema.value("hello");
expect(value).toBe("hello");
expect(
function(){
schema.value();
})
.toThrow(new Error("Value is required."));
expect(
function(){
schema.value("hello world");
})
.toThrow(new Error("The maximum value allowed is 5."));
var isValid = schema.isValid("");
expect(isValid).toBe(false);
var isValid = schema.isValid("hello");
expect(isValid).toBe(true);
var isValid = schema.isValid("hello world");
expect(isValid).toBe(false);
Example Object Schema
Objects schema is set by applying rules to each property of the object. You can also use regular expressions on
the schema object keys to give better filtering.
You can also set the schema object keys to primitive values which will be interpreted as required().default(value)
in the schema.
var Schema = Divhide.Schema;
var schema =
Schema.object({
"/^optional/" : Schema.string().optional(),
"number" : 0,
"string" : "",
})
.required()
.compile();
var value = schema.value({
string : "awesome!",
number : "0",
optional1 : "1",
optional2 : "2",
other : 1
});
expect(value).equals({
"number": 0,
"string": "awesome!",
"optional1": "1",
"optional2": "2"
});
Example Array Schema
The following example describe an array rule that is optional and its expecting three items.
var Schema = Divhide.Schema;
var schema = Schema
.array([ Schema.string().default("value"), Schema.number(), Schema.string() ])
.optional()
.compile();
var value = schema.value();
expect(value).toBe(null);
value = schema.value([ '1', 2, '3' ]);
expect(value).equals([ '1', 2, '3']);
expect(
function(){
schema.value([ '1', 2, '3', 4, 5, 6 ])
})
.toThrow(
new Error("Expected list with 3 items but found 6.")
);
expect(
function(){
schema.value(10);
})
.toThrow(
new Error("'array' was expected but found 'number' instead.")
);
var schema = Schema
.array([ Schema.string(), Schema.number() ])
.repeatable()
.optional()
.compile();
var value = schema.value(["1", 2, "3", 4]);
expect(value).equals(["1", 2, "3", 4]);
expect(
function(){
schema.value(["1", 2, "3"])
})
.toThrow(
new Error("Expected list length to be multiple of 2 but found length of 3.")
);
CustomSchema
Type
Type facility provides an API that can help you with typical operations using the javascript
data Types.
Methods
Gets the string representation of the given value.
-
Type.isArray(value)
-
Type.isBoolean(value)
-
Type.isFunction(value)
-
Type.isString(value)
-
Type.isObject(value)
-
Type.isBoolean(value)
-
Type.isRegExp(value)
-
Type.isRegExpStr(value)
-
Type.isNumber(value)
-
Type.isDefined(value)
Checks if the value is defined.
Checks if the value is empty (executed in string, list and object context ).
var Type = Divhide.Type;
var type = Type.of({});
expect(type).toBe("object");
var type = Type.of([]);
expect(type).toBe("array");
var type = Type.of(1);
expect(type).toBe("number");
var type = Type.of("name");
expect(type).toBe("string");
var type = Type.of(true);
expect(type).toBe("boolean");
var isArray = Type.isArray([]);
expect(isArray).toBe(true);
var isBoolean = Type.isBoolean(true);
expect(isBoolean).toBe(true);
var isFunction = Type.isFunction(function(){});
expect(isFunction).toBe(true);
var isString = Type.isString("");
expect(isString).toBe(true);
var isObject = Type.isObject({});
expect(isObject).toBe(true);
var isObject = Type.isObject(null);
expect(isObject).toBe(false);
var isRegExp = Type.isRegExp(/reg/);
expect(isRegExp).toBe(true);
var isNumber = Type.isNumber(1);
expect(isNumber).toBe(true);
var isNumber = Type.isNumber("1.1");
expect(isNumber).toBe(true);
var isDefined = Type.isDefined(null);
expect(isDefined).toBe(false);
var isDefined = Type.isDefined(undefined);
expect(isDefined).toBe(false);
var isEmpty = Type.isEmpty("");
expect(isEmpty).toBe(true);
var isEmpty = Type.isEmpty([]);
expect(isEmpty).toBe(true);
var isEmpty = Type.isEmpty({});
expect(isEmpty).toBe(true);
var isEmpty = Type.isEmpty(null);
expect(isEmpty).toBe(true);
Safe
Safe facility provides an API that can helps you safelly working with javascript data types. This methods
are supposed to work with different value types.
Methods
Safe.array(value, defaultValue?)
Gets the value in the array representation. defaultValue is returned if defined and if value is not
an array.
-
Safe.boolean(value, defaultValue?)
-
Safe.string(value, defaultValue?)
-
Safe.object(value, defaultValue?)
-
Safe.number(value, defaultValue?)
-
Safe.function(value, defaultValue?)
-
Safe.value(value, defaultValue?)
-
Safe.regexp(value, defaultValue)
-
Safe.instanceOf(value, Class)
Gets an instance of the given value if is an instance of the given Class, otherwise it will
create an instance.
Gets the length of the value.
Safe.coerce(value, expected)
Gets the value coerced by the expected value type.
Example Array
var Safe = Divhide.Safe;
var value = Safe.array(1);
expect(value)
.equals([1]);
var value = Safe.array(1);
expect(value)
.equals([1]);
var value = Safe.array([1, 2]);
expect(value)
.equals([1, 2]);
var value = Safe.array(null, [ 1, 2 ]);
expect(value)
.equals([1, 2]);
var value = Safe.array("1", [1, 2]);
expect(value)
.equals(["1"]);
Example Boolean
var Safe = Divhide.Safe;
var value = Safe.boolean(true);
expect(value).toBe(true);
var value = Safe.boolean(false);
expect(value).toBe(false);
var value = Safe.boolean(1);
expect(value).toBe(true);
var value = Safe.boolean("1");
expect(value).toBe(true);
var value = Safe.boolean("0");
expect(value).toBe(false);
var value = Safe.boolean({});
expect(value).toBe(false);
var value = Safe.boolean({}, true);
expect(value).toBe(true);
var value = Safe.boolean([]);
expect(value).toBe(false);
var value = Safe.boolean(null);
expect(value).toBe(false);
Example Function
var Safe = Divhide.Safe;
var fn = Safe.function(function(){});
expect(fn())
.toBe(undefined);
var fn = Safe.function("");
expect(fn())
.toBe(undefined);
var fn = Safe.function("", function(){ return 1; });
expect(fn())
.toBe(1);
Example Length
var Safe = Divhide.Safe;
var value = Safe.length([1, 2]);
expect(value).toBe(2);
var value = Safe.length({ one: 1, two: 2});
expect(value).toBe(2);
var value = Safe.length(2);
expect(value).toBe(2);
var value = Safe.length("hello");
expect(value).toBe(5);
Example Number
var Safe = Divhide.Safe;
var value = Safe.number(1);
expect(value).equals(1);
var value = Safe.number("");
expect(value).equals(0);
var value = Safe.number("1");
expect(value).equals(1);
var value = Safe.number({});
expect(value).equals(0);
var value = Safe.number("", 1);
expect(value).equals(1);
Example Object
var Safe = Divhide.Safe;
var value = Safe.object({ one: 1 });
expect(value).equals({ one: 1 });
var value = Safe.object([]);
expect(value).equals({});
var value = Safe.object([], { one: 1 });
expect(value).equals({ one: 1 });
Example Regex
var Safe = Divhide.Safe;
var value = Safe.regexp(/regexp/);
expect(value)
.toEqual(/regexp/);
var value = Safe.regexp("/regexp/");
expect(value)
.toEqual(/regexp/);
var value = Safe.regexp("");
expect(value)
.toEqual(/^$/);
var value = Safe.regexp("name");
expect(value)
.toEqual(/^name$/);
var value = Safe.regexp({}, /regexp/);
expect(value)
.toEqual(/regexp/);
Example String
var Safe = Divhide.Safe;
var value = Safe.string("");
expect(value).toBe("");
var value = Safe.string({});
expect(value).toBe("");
var value = Safe.string({}, "default");
expect(value).toBe("default");
Example Value
var Safe = Divhide.Safe;
var value = Safe.value(1);
expect(value).toBe(1);
var value = Safe.value("1");
expect(value).toBe("1");
var value = Safe.value(null);
expect(value).toBe(null);
var value = Safe.value(undefined);
expect(value).toBe(null);
var value = Safe.value(null, 1);
expect(value).toBe(1);
Obj
Object facility provides some utility function to use on Objects.
Methods
Returns an array with all the keys that match the filter.
Example
var Obj = Divhide.Obj;
var results = Obj.filter({ "one": 1, "two": 2 });
expect(results)
.toEqual(["one", "two"]);
var results = Obj.filter({ "one": 1, "two": 2 }, "one");
expect(results)
.toEqual(["one"]);
var results = Obj.filter({ "one": 1, "two": 2 }, "three");
expect(results)
.toEqual([]);
Arr
Array facility provides an API to easily manage array references.
Methods
Gets the value of the index.
-
first(value)
-
last(value)
-
length(value)
-
insert(array, value, index?)
Inserts the given value(s) on the given index of the array.
-
remove(array, index, n?)
Removes the given n elements from the index from the array.
Example
var Arr = Divhide.Arr;
var value = Arr.index([1 ,2, 3], 0);
expect(value).toBe(1);
var value = Arr.index([1 ,2, 3], 10);
expect(value).toBeNull();
var first = Arr.first([1 ,2, 3]);
expect(first).toBe(first);
var last = Arr.last([1 ,2, 3]);
expect(last).toBe(3);
var length = Arr.length([1 ,2, 3]);
expect(last).toBe(3);
var array = [1, 2, 3];
Arr.insert(array, 4);
expect(array).toEqual([1, 2, 3, 4]);
var array = Arr.insert([1 ,2, 3], [4, 5]);
expect(array).toEqual([1, 2, 3, 4, 5]);
var array = Arr.insert([1 ,2, 3], -1, 0);
expect(array).toEqual([-1, 1, 2, 3]);
var array = [1, 2, 3];
Arr.remove(array, 0);
expect(array).toEqual([2, 3]);
var array = [1, 2, 3];
Arr.remove(array, 0, 2);
expect(array).toEqual([3]);
Contribute
Testing
The purpose of the project is to provide a library that can be used across every platform that uses javascript. The tests are done using jasmine and using the browser to debug. Every file save on the "src" folder will recompile
the browserify bundle.
grunt dev
Build
The build process will run a set of tasks including linting and testing. To contribute please add
tests to the fix/feature you've worked.
Also, when building the documention is compiled into the README.md. Each module iniside the "src" directory
should contain a ".md" file to document it's behaviour.
The following command will run the build.
grunt
Release
grunt pre-release
grunt release
grunt deploy
Authors
Oscar Brito
License
Copyright (c) 2015 Oscar Brito aetheon@gmail.com, contributors.
Released under the license