ecmamodel.ts
TypeScript Model and Collection with validation,error handling and sync them with your existing API over a RESTful JSON interface.
ecmamodel.ts is a open source package for the node.js and browser.
Installation
$ npm install --save ecmamodel.ts
Requirements
ecmamodel.ts requires a Javascript environment with TypeScript classes and decorators.
Note.
On old browsers we are recommending to use babel-polyfill and isomorphic-fetch
Usage
Defining Model
Your all models should be extended from Model class.
Model fields should be defined by @Field decorator. Field annotation takes optional properties which describe field
;
Type of field should be defined with type properties available in Field annotation.
Available Field Types With Options
String
-
lowercase
: {Boolean} calls .toLowerCase() method on the value -
uppercase
: {Boolean} calls .toUpperCase() method on the value -
trim
: {Boolean} calls .trim() method on the value -
match
: {RegExp} creates a RegExp based validator. -
enum
: {Array} Creates an enum validator. If the value which is being set to the field is not in the Array, validation will fail. -
minLength
: {Number} Creates an min length validator. If the value is shorter than the minimum allowed length, validation will fail. -
maxLength
: {Number} Creates an max length validator. If the value is longer than the maximum allowed length, validation will fail.
Number
-
min
: {Number} creates a validator which checks that the value which is being set is not less than the value specified. -
max
: {Number} creates a validator which checks that the value which is being set is not greater than the value specified.
Date
-
min
: {Date} creates a validator which checks that the value is before minimum allowed value. -
max
: {Date} creates a validator which checks that the value is after maximum allowed value.
Boolean
- no custom options
Array
- no custom options
Object
- no custom options
Additional options
-
default
. will populate the field when it is created. -
required
:{Boolean} validates if the value exists. -
validators
:{Array} define custom validators with custom errors message. -
set
:{Function} define field setter
for example.
name:String; ob.name = 'JOHN' // will return 'john'.
Type Casting
Each property in our Model will be casted to its associated type For example, we've defined a age as a String which will be cast to the Number and so on.
age:Number; ob.age = '15' // automatically cast values to Number (15)
Custom Validators With Error Handling
Your validators should be extended from Validator class. and errors with ValidationError class
;;
Validator supports synchronous and asynchronous validations.
;
And it's should be defined within validators
option. for example
Validation work when validate() function is called
;user.validate;
OR
;user.validate.then.catch;
Defining Model Id (unique identifier)
default id field is (id). but you can override it by using @Id decorator. For example.
;
You can have only one @Id field in each model
Defining Models Collection
Your Models collection should be extended from Collection class. Collection constructor requires Model's class.
; // we can add,remove and get model from collection ;collection.add;;;collection.removeuser; //also we can reset,cleanup,clear callection data collection.resetcollection.clear;collection.cleanup
API Integration
ecmamodel.ts is pre-configured to sync with a RESTful APIs. Simply create a new Model with the url of your resource endpoint: You should override Model's and Collection's url getters. Getters should return endpoint urls
;user.name = "John";user.save.then.catch
The Collection and Model components together form a direct mapping of REST resources using the following methods:
-
GET /users/ .... collection.fetch();
-
POST /users/ .... model.save();//if it's new
-
GET /books/1 ... model.fetch();
-
PUT /books/1 ... model.save();
-
DEL /books/1 ... model.destroy();
After API's success response model and collection call 'parse()' method so you can transform data
} ;user.name = "John";user.save;
Events
ecmamodel.ts Model and Collection have custom named events.
Available Events
collection events
create
when a model is added to a collection.remove
when a model is removed from a collection.change
when model's fields are changedreset
when the collection's entire content has been reset (removed all the objects).
model events
change
when a model's fields have changed.change:[field]
when a specific field has been updated.validate
when validate function is calleddestroy
when a model is destroyed.sync
when a model or collection has been successfully synced with the server.error
when a model's or collection's request to the server has failed.response
when a model or collection receives response to its request from the server.
Examples
model: create,update and validate
; ; ;user.on'change',;user.on'change:name',;user.name = 'Smith'; user.on'validate',;user.name = 'wrong name';user.validate;//oruser.validate .then .catch
collection: create and remove item
; ; ;collection.on'create',collection.on'renove',collection.add//or;collection.addmodel //get item;//or; //remove itemcollection.removeuser;//orcollection.remove
sync with server
;;//include for old browsers and node.js support ; ;user.on'sync',;user.on'response',;user.on'save',; user.save .then .catch //will send 'POST' request to "POST /users" with user data user.fetch //will send 'GET' request to "GET /users" with query string//with options patch user.fetch({patch:true}) will send PATCH request//oruser.fetch // default is 'GET'
They also works on Collections
collection
Model Available methods
- get(key) - get Model by field name
- set(key,value,silent) - set new value for a specified field; if 'silent' is true, changes won't be triggered
- toJSON()
- validate(cb:Function)
- save(options={validate:true})
- getId()
- parse(res)
- get url() (server endpoint) should be overridden
- get isNew
Collection Available methods
- get(id)
- add(object)
- remove(object)
- clear()
- cleanup(cb:Function)
- reset(data:Array)
- fetch(options)
- parse(res)
- map(cb:Function)
- filter(cb:Function)
- each(cb:Function)
- sort(cb:Function)
- toObject()
- toArray()
- toJSON()
- get url() (server endpoint) should be overridden
- length
UTILS
ecmamodel.ts utility classes are located in 'ecmamodel.ts/lib/utils'