0.1.0 • Published 2 years ago
flex-mapper v0.1.0
flex-mapper
TypeScript library for mapping objects and classes.
Usage
Installation:
npm i flex-mappermap function
Maps objects
import { map } from 'flex-mapper';
...
const cat = {
name: "Tom",
color: "gray",
years: 2
}
const result = map(cat, {
name: 'nickname',
color: value => value.toUpperCase(),
years: [value => value * 12, "months"]
});
console.info(result);
// {
// nickname: "Tom",
// color: "GRAY",
// months: 24
// }map class
Destination class definition. Mapping options are described with decorators: @mapProperty and @mapConvert.
import { mapProperty, mapConvert } from 'flex-mapper';
...
class CatClass {
@mapProperty("name")
nickname: number;
@mapConvert(value => value.toUpperCase())
color: string;
@mapProperty("years", value => value * 12)
months: number;
}Mapping class object:
import { map } from 'flex-mapper';
...
const cat = {
name: "Tom",
color: "gray",
years: 2
}
const result = map(cat, CatClass);
console.info(result);
// {
// nickname: "Tom",
// color: "GRAY",
// months: 24
// }This is important to pass the class type as a second parameter. In this way map method reads decorators defined inside the class.
mapProperty decorator
Describes how the property is to be mapped.
Parameter is an interface with properties:
| Name | Type | Description |
|---|---|---|
| source | string | Source property name |
| convert | function or string | In function case, parameter is source value the function result is definition value. In string case, possible values are: number, string. |
mapConvert decorator
Has one function or string parameter for converting.