1.2.0 • Published 6 years ago

ts-model-serializer v1.2.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 years ago

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;
 }
}
1.2.0

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago

0.0.0

6 years ago