This package has been deprecated

Author message:

WARNING: This project has been renamed to ts-data-serializer. Install using ts-data-serializer instead.

ts-model-serializer
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

TypeScript Model Serializer

Travis Coverage Status Donate

A Model Deserializer for Typescript that maps up JSON response to a class model.

Usage

npm install -save ts-model-serializer

Extend every model class with the Serializer class:

export class Test extend Serializer<Test>

Map a single property

@Mapper() book: Book;

or if the JSON response has a different name from the property name

@Mapper('test-book') book: Book;

Map an object

@Mapper(width: 'book-width', height: 'book-height')
size: {width: number, height: number}

Transform value after mapping

@Mapper('book')
set title(book: Book) {
 this._title = book.title.toLowerCase();
}

Run the Deserializer

new Test().deserialize(input);

Where "input" is the JSON response and "Test" is your model.

Debugging and handling of missing keys

The serializer autodetects missing keys and stores them in "missingKeys".
This can be used in your custom model to handle the missing keys accordingly.

export class Test extend Serializer<Test> {
  @Mapper('name') name: string;
 
  greet(): string {
    if (this.missingKeys.includes('name')) {
      return 'missing name :(';
    }
 
    return this.name;
  }
}

By using the strict serializer, an error message will print if a key is missing.
The strict serializer can be used by adding the "StrictSerializer" mode instead of "Serializer":

export class Test extend StrictSerializer<Test>

A normal serializer can also be used as strict by setting the "strict" property
before deserializing:

export Test extend Serializer<Test> {
 constructor() {
   super();
   this.strict = true;
 }
}

Package Sidebar

Install

npm i ts-model-serializer

Weekly Downloads

0

Version

1.2.0

License

MIT

Unpacked Size

15.7 kB

Total Files

15

Last publish

Collaborators

  • bagera