ClassJS
Business and Data Access layers for browsers or nodejs
Install
- NodeJS
- Standalone:
$ npm install atma-class
var Class = require('atma-class')
- AtmaPackage
- Standalone:
- Browser
<script src='//cdn.jsdelivr.net/classjs/1.0.66/class.min.js'></script>
- Attributes Overview
- Serialization
- Collections
- Persistence
- RESTful
- Local Storage
- MongoDB
- MySQL in progress
- Repository
- Static Functions
- Validation
- Classes
Attributes
Class definition object is a simple prototype
object, but with Attributes
it is possible to add or change some functionality of the resulted class, like inheritance, overrides, persistance, validation and some more.
;
Serialization
A Class
instance can be serialized to or deserialiazed from a string or simple JSON object. For this to happen, the instance schould be inherited from a Serialization
class.
var Foo = ;var foo = baz: 'Baz';foobaz === 'Baz';
There could be also some meta specified
var Foo = ; var jsonStr = '{"date":"2014-03-27T23:33:45.594Z","user":{"name":"baz"},"yourKey":5}';var foo = jsonStr; foodate instanceof Date //> truefoouser instanceof User //> truefoomyKey === 5 //> true
Collections
Creates Array-like Object with all class features
var Users = Class; var list = Users ; ;
Store
Storage Interface is same for all types, so you can easily switch between local storage, Ajax or MongoDB.
Remote
async - extends Class.Deferred
var User = ; // resolve user (GET)var user = User ; // update (PUT) or Save (POST) - (look for existance of id/_id properties);username = 'X';user ; // Remove (DELETE)user // patch object (PATCH) - MongoDB update query syntax is useduser ; // Static service comunicationvar user = username: 'baz' age: 40;Class Remote ;
More route samples can be found from tests Route Tests
LocalStore
sync, as localStorage is synchronous - but also inherits from Class.Deferred
var Settings = ;var setts = ;// getsetts;// save or updatesettspoints = 10;setts;// removesetts;// patchsetts;
MongoDB
// settings:ClassMongoStore;// var User = ;var Users = Class; var user = User // .fetch({ age: '>10' })// .fetch({ age: { $gt: 10 }}) // Complex queries with options. (Use $query from MongoDB API)Users ; userusername = 'foo'// save or update if `_id` is present.user ;// deleteuser ;// patchuser ; // Any MongoDB queries: // 1) Get MongoDB `db` objectClass MongoStore ; // 2) Get MongoDB `collection` objectUser ;
All work with the database is encapsulated, so you do not need even to connect to the database, just apply settings and with the first query the connection will be established.
Indexes
var User = ;// ensure indexesClass MongoStore //=> Deferred // as all indexes being tracked, you can apply all indexes at onceClass MongoStore //=> Deferred
Advanced connections and settings:
Class MongoStore
Profiler
Enable profiler to catch all slow, unindexed queries and updates.
Class MongoStore profiler
Repository
Namespaces When declaring a Class, it can be stored in the repository object for simpler access.
MaskJS.Node profits of this feature to automatically serialize (server-side) and deserialize (browser) class instances.
var User = ; User === === ClassModelUser; // redefine the repository objectClass; User === === ModelUser;
Static Functions
-
Class.validate(object [, ?validationModel, ?isStrict])
#validationModel
- (@see Validation) - is not required, if instance/object hasValidate
attribute.isStrict
- Boolean - return error if object contains property, which is not defined invalidationModel
returns error object if the instance is invalid or nothing (
void 0
) if is ok. -
Class.properties(Ctor | instance)
#return hash of all properties with types if known.
-
Class.keys(instance)
#return array of properties (without methods and private props)
-
Class.stringify(instance)
#Serializes the instance. If class has name, the name is included, for later deserialization and initialization
-
Class.parse(string)
#Deserializes instance. e.g - serialize models on NodeJS, pass them to the front-end and restore the models there.
var User =;var user = name: 'baz';user; //> 'baz'var str = Class //> {"name":"baz","__$class__":"User"}...var user = Class;user //> 'baz'
Validation
Validation Model
// required, not empty string foo: 'string' // required, of type number foo: 'number' // required, validate with regexp age: /^\d+$/ // required, custom check function (return 'nothing' if ok) { if value % 2 !== 0 return 'Only even numbers'; } // optional. Same value types as by 'required' '?baz': 'number' // unexpect. Same value types as by 'required' '-quz': null // validate subobject jokers: left: 'number' right: 'number' // validate arrays collection: _id: 'string' username: 'string'
-
Class Validation
var Foo =;var foo = ;var error = Class; -
Simple object validation
var user = username: 'foo'var error = Class;
Classes
There are some classes you can start to use.
Deferred
Promise
/Defer
implementation
Usage example
// 1) Create deferrable classvar X = ;var dfr = ; // 2) Create simple deferrable objectvar dfr = ; // 3) Create simple deferrable object with factory functionvar dfr = ClassDeferred; // 3) Create deferrable delegatevar fn = ClassDeferred); var dfr = ; // 4) Memoize deferrable delegate (with same arguments function is called only once)var fn = ClassDeferred); var dfr1 = ;var dfr2 = ;dfr1 === dfr2; //> true Deferred __proto__ // callbacks are called once :Self, fail : function(callback):Self, always: function(callback):Self, resolve: function(...args):Self, reject : function(...args):Self // reset deferred object and move to unresolved state defer : function():Self pipe : Function // pipe Self states to this deferred instance = function(Deferred):Self // Returns new Deferred which depends on Filter functions // @see Filter meta = function(doneFilter, failFilter): new Deferred // create the delegate function, which will resolve or reject the deferred object when called, // first argument pipeCallback: function(): function // alias to .pipe(function, function) then : function(doneFilter, dailFilter):new Deferred, // check state isResolved: function():Boolean, isRejected: function():Boolean isBusy : function():Boolean}; doneFilter/failFilter : Function // modify or override // `pipe` and `then` deferreds are resolved then with this modified values = : Any // return another Deferred array to listen for // `pipe` and `then` deferreds are bound to this deferred return value = function(): Deferred Deferred __static__ {
EventEmitter
var X = ;;; EventEmitter __proto__ :Self, // alias to `emit` fn trigger: function(...args):Self, on: function(event, callback):Self, once: function(event, callback):Self, off: function(event, callback):Self, // create Function which trigger specific event when is called // fn(...args) ~~ x.trigger(event, ...args); pipe: function(event): function }
Run tests and build
$ npm install$ npm test # build $ atma
(c) 2014 MIT