Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Typed data models, mappers and adapters

NotificationsYou must be signed in to change notification settings

shlomiassaf/tdm

Repository files navigation

Build Status

TDM - Typed data models

A TypeScript transformation framework. Highly extensible, super typed.

Given a data structure, instructions and some logic we can do a lot.
Transform an object into an http request and and incoming payload into an object or maybe a model into a form?

Transformation can be cosmetic or even 1:1 but can also completely change the way an object looks like.

TDM is is a collection of libraries that use Models, Meta-Programming and adapters to abstract away mundane by natively describing schematic rules that translate into operations.

@Exclude()exportclassMyModel{   @Identity()  @Prop()id:number;    @Prop()name:string;}

In words, the code above says:
There is adata structure / Model calledMyModel that has 2 properties:id andname.
MyModel is strict (@Exclude) so only selected properties can play the transformation game.
The propertyid is also the identity (@Identity()).

Reviewing the opening statement:

Given a data structure, instructions and some logic we can do a lot.

Ourdata structure / Model is the class.Theinstructions / Meta-Programming are part of the model defined via decorators.

We can now use logic units (adapters) to transform the model.
We can change the logic units or build custom logic.
We can extends the required instructions to supports more complex logic units.

TDM is built on top of the low level libraries@tdm/tixin,tdm/transformation,@tdm/core.

TDM relays on adapters, currently the only adapter is for Angular 2.

Status - Alpha.

Main packages:

@tdm/transformation

Extensible metadata storage and a Class transformation library (serialize / deserialize)

@Exclude()exportclassMyClass{   @Identity()  @Prop()id:number;    @Prop()name:string;}

Supports custom mapping (transforming) implementations.Comes with a built in direct mapper. Direct mapping means 1:1 mapping, no schema or document structure.

A JSON API mapper can be used in@tdm/json-api-mapper

Create custom mappers by implementing the required interface.

@tdm/transformation comes with basic relationship (@Relation) support.

@tdm/core

Core library, extends@tdm/transformation.@tdm/core comes with a lot of features...

  • Customizable Action based commands
  • Build in CRUD actions
  • Advanced Relationships (BelongsTo, Owns)
  • Static/instance level Actions (e.g.:query is always static)
  • Hooks for built in actions
  • Adapter architecture
  • Event stream (using observables)
  • DAO pattern
  • Active records pattern with full Type support. (plugin, need to opt in)
  • more..

@tdm/angular-forms-mapper (name might change)

Map data models defined with@tdm/transformation and@tdm/core into and back from@angular/formsFormGroup /FormArray

@tdm/angular-http (name might change)

An adapter implementation for the angular (2) library.

With@tdm/angular-http Model classes become Resource much like in angular 1ng-resource but now with full typescript Type support for model properties, methods and Active record methods.

This is an Active record implementation, you can also go pure and use a DAO leaving your models clean.

@HttpResource({endpoint:'/api/users/:id?',urlParams:{limit:'5'// not in endpoint so will fallback to query string},noBuild:true})classUser_{  @Identity()  @UrlParam({// optionally set what methods to use the param on.methods:[HttpActionMethodType.Get,HttpActionMethodType.Delete,HttpActionMethodType.Patch,HttpActionMethodType.Put]})id:number;// this will go into the "endpoint" from the instance!  @Prop({validation:{// custom validationname:'test-validator',validate(ctx){returnfalse;},errorMessage(ctx){return'validation error';}}})username:string;  @Prop({alias:'motto_abc'// server returns motto_abc})  @Exclude()motto:string;constructor(){}  @Hook({event:'before',action:'$refresh'})bfRef(){console.log('BeforeRefresh');}  @HttpAction({// custom HTTP actionsmethod:HttpActionMethodType.Get,raw:{handler:User_.prototype.rawDeserializedHandler,deserialize:true}})rawDeserialized:(options?:HttpActionOptions)=>RestMixin<User_>;privaterawDeserializedHandler(resp:ExecuteResponse,options?:HttpActionOptions){}  @HttpAction({method:HttpActionMethodType.Get,raw:User_.prototype.rawHandler})raw:(options?:HttpActionOptions)=>RestMixin<User_>;privaterawHandler(resp:ExecuteResponse,options?:HttpActionOptions){}  @Hook({event:'before',action:'query'})// static hooks (for static actions, like query)staticbfQuery(this:ActiveRecordCollection<RestMixin<User_>>){this.$ar.next().then(coll=>{console.log(`BeforeQuery-AfterQuery: got${coll.collection.length}`)});console.log('BeforeQuery');}  @ExtendAction({// extending a built in action, useful if you need the user to provide more params)pre:(ctx:ExecuteContext<any>,id:IdentityValueType,a:number,b:number,options:HttpActionOptions)=>{ctx.data[ctx.adapterStore.identity]=id;returnoptions;}})staticfind:(id:IdentityValueType,a:number,b:number,options?:HttpActionOptions)=>RestMixin<User_>;}exportconstUser=RestMixin(User_);exporttypeUser=RestMixin<User_>;

You can also do

@HttpResource({endpoint:'/api/users/:id?',urlParams:{// there are hard coded paramslimit:'5'// not in path so will go to query string (?param=15)},})exportclassUserextendsRestMixin(User_){}

TDM supports multiple ways to declare a Resource, you can see them all insrc/demo/resource/Users
UsingRestMixin is mandatory, at least until the TypeScript team will implement type reflection forClassDecorator

@tdm/angular-http Supports AOT but currently Resources are not injectable!

You can then use the resources:

User.find(2).username;// OKconstuser:User=newUser();// OKuser.id=15;user.$refresh().username;// OKuser.$refresh().abcd;// SHOULD ERROR// Using async system with promises:user.$ar.next().then(u=>u.id);// OKuser.$ar.next().then(u=>u.f34);// SHOULD ERROR// hadnling collections, coll.collection is of type User[]UserBaseClass.query().$ar.next().then(coll=>coll.collection);// OKUserBaseClass.query().$ar.next().then(coll=>coll.sdfd);// SHOULD ERROR// Using async system with observablesuser.$ar.events$.subscribe(...)// `$events` is an observable of resource events (succes, failure, cancelled etc...)// Cacnellinguser.$ar.cancel()// disconnecting all observablesuser.$ar.disconnect()// busy (in-flight) indicatoruser.$ar.busy// true / false// busy (in-flight) indicator STREAMuser.$ar.busy$.subscribe(...)// true / false

The$ar object is an optional extension, you can opt in viaimport '@tdm/core/add/active-record-state';

The promise extensionnext() is optional extension, you can opt in viaimport '@tdm/core/add/active-record-state/next';

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp