meta-transformer
v2.0.1
Published
meta-transformer
Downloads
7
Readme
What is meta-transformer?
meta-transformer is a lightweight (1k gzipped), tree-shakable, zero dependency library for transforming plain JavaScript objects to class instances. It is isomorphic and can be used with NodeJs or in a browser.
Installation
Install the meta-transformer package from npm.
npm install meta-transformer
Usage
class Widget {
name: string;
model: number;
created: Date;
}
const classInstance: Widget = MetaTransformer.toClass<Widget>(Widget, {
name: "Doodad",
model: 1234,
created: new Date()
});
You can also transform arrays in the same way.
const classArray: Widget[] = MetaTransformer.toClass<Widget>(Widget, [
{
name: "Doodad",
color: "Blue",
model: 1234
},
{
name: "Thing",
color: "Red",
model: 9876
}
]
);
Transforming Nested Objects
You can use the @Transform(<class type>)
to transform nested complex objects.
class WidgetDetail {
material: string;
shape: string;
}
class Widget {
name: string;
color: string;
model: number;
@Transform(WidgetDetail)
detail: WidgetDetail;
}
const classInstance: Widget = MetaTransformer.toClass<Widget>(Widget, {
name: "Doodad",
color: "Blue",
model: 1234,
detail: {
material: "Plastic",
shape: "Square"
}
);
Exclude Properties
You can use the @Exclude()
decorator to exclude properties from transformation.
class Widget {
name: string;
color: string;
@Exclude()
model: number;
}
const classInstance = MetaTransformer.toClass<Widget>(Widget, {
name: "Doodad",
color: "Blue",
model: 1234
});
// The transformed classInstance is {"name":"Doodad","color":"Blue"}
Circular Dependencies
meta-transformer will throw an error if you try to transform objects that have circular dependencies.