mapping-factory
v1.0.1
Published
Object converter
Downloads
1
Readme
mappingFactory
Object converter
Install
npm install mapping-factory
Getting Started
import {
lowerCamelCaseProvider,
defaultArrayProvider
} from './DefaultProviders';
import { MappingFactory } from './MappingFactory';
// #region DEMO Object
class Hummer {
Name: string;
Country: string;
Children: Hummer[];
}
class Hummer2 {
name: string;
country: string;
children: Hummer2[];
}
const sourceChild1 = new Hummer();
sourceChild1.Name = 'B';
sourceChild1.Country = 'JP';
const sourceChild2 = new Hummer();
sourceChild2.Name = 'C';
sourceChild2.Country = 'US';
const source = new Hummer();
source.Name = 'A';
source.Country = 'TW';
source.Children = [sourceChild1, sourceChild2];
// #endregion
// register lower camel case
MappingFactory.register(lowerCamelCaseProvider);
// result: {"name":"A","country":"TW","children":[{"name":"B","country":"JP"},{"name":"C","country":"US"}]}
console.log(
JSON.stringify(MappingFactory.convert(source, lowerCamelCaseProvider.name))
);
// clean all providers (and default provider)
MappingFactory.clearProviders();
MappingFactory.register(defaultArrayProvider);
// register custom provider
MappingFactory.register({
name: 'HummerToHummer2',
sourceType: Hummer,
targetType: Hummer2,
convert: (input: Hummer, convert) => {
const result = new Hummer2();
result.name = convert(input.Name); // convert method == MappingFactory.convert
result.country = convert(input.Country);
result.children = convert(input.Children);
return result;
}
});
MappingFactory.register({
name: 'boxingStringToArray',
sourceType: String,
targetType: Array,
convert: (input: string) => {
return [input];
}
});
// result: {"name":["A"],"country":["TW"],"children":[{"name":["B"],"country":["JP"]},{"name":["C"],"country":["US"]}]}
console.log(JSON.stringify(MappingFactory.convert(source)));