Home Reference Source Test

Data Scheme

Data Model framework based on ECMAScript Decorator proposal

NPM Dependency Build Status

NPM

Basic Example

User.js

import Model, { mapGetter, is, Range, Email, Phone, URL } from 'data-scheme';


@mapGetter
export default  class User extends Model {

    @is(/^[\w-]{3,20}$/, '')
    set name(value) {  this.set('name', value);  }

    @is(Email, '')
    set email(value) {  this.set('email', value);  }

    @is( Phone )
    set phone(value) {  this.set('phone', value);  }

    @is([0, 1, 2],  2)
    set gender(value) {  this.set('gender', value);  }

    @is(Range( 1900 ))
    set birthYear(value) {  this.set('birthYear', value);  }

    @is(URL, 'http://example.com/test.jpg')
    set avatar(value) {  this.set('avatar', value);  }

    @is( URL )
    set URL(value) {  this.set('URL', value);  }

    @is( String )
    set description(value) {  this.set('description', value);  }
}

index.js

import User from './User';

const user = new User({
    name:   'test',
    email:  '[email protected]'
});

user.phone = '+86-028-88888888';

console.log( user.valueOf() );

Console output

{
    "name": "test",
    "email": "[email protected]",
    "gender": 2,
    "avatar": "http://example.com/test.jpg",
    "phone": "+86-028-88888888"
}

Installation

npm install data-scheme @babel/polyfill

npm install -D \
    @babel/cli \
    @babel/core \
    @babel/preset-env \
    @babel/plugin-proposal-decorators

.babelrc

{
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        [
            "@babel/plugin-proposal-decorators",
            {
                "decoratorsBeforeExport": true
            }
        ]
    ]
}

Advanced usage

Observe Values changing

import User from './User';

const user = new User({
    name:   'test',
    email:  '[email protected]'
});

user.observe({
    name(value, oldValue) {

        console.log(value, oldValue);    //  'example' 'test'
    }
});

user.name = 'example';

Decorator hook

hook.js

import { listen } from 'data-scheme';

listen('HTTP',  ({Class, method, path, contentType}) =>
    console.log(Class, method, path, contentType)
);

User.js

import Model, { mapGetter, HTTP } from 'data-scheme';

@HTTP('POST', '/user')
@HTTP('GET', '/user')
@mapGetter
export default  class User extends Model {
    //  Field defination
}

index.js

import './hook';

import User from './User';

Learn more

  1. Meta programming

  2. Decorator API (Stage-2)