Gathering detailed insights and metrics for class-transformer
Gathering detailed insights and metrics for class-transformer
Gathering detailed insights and metrics for class-transformer
Gathering detailed insights and metrics for class-transformer
class-transformer-validator
A simple wrapper around class-transformer and class-validator which provides nice and programmer-friendly API.
@buka/class-transformer-extra
class-transformer-extra contains methods that's aren't included in the class-transform package.
@nestjs/class-transformer
Fork of the class-transformer package. Proper decorator-based transformation / serialization / deserialization of plain javascript objects to class constructors
@hippo-oss/class-decorators
DTO decorators with class-transformer and class-validator.
Decorator-based transformation, serialization, and deserialization between objects and classes.
npm install class-transformer
100
Supply Chain
99.2
Quality
78.3
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
6,912 Stars
771 Commits
503 Forks
42 Watching
14 Branches
58 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
TypeScript (99.64%)
JavaScript (0.36%)
Cumulative downloads
Total Downloads
Last day
-2.6%
849,751
Compared to previous day
Last week
2.6%
4,783,710
Compared to previous week
Last month
11.4%
19,742,585
Compared to previous month
Last year
34.3%
191,829,257
Compared to previous year
No dependencies detected.
Its ES6 and Typescript era. Nowadays you are working with classes and constructor objects more than ever. Class-transformer allows you to transform plain object to some instance of class and versa. Also it allows to serialize / deserialize object based on criteria. This tool is super useful on both frontend and backend.
Example how to use with angular 2 in plunker. Source code is available here.
In JavaScript there are two types of objects:
Plain objects are objects that are instances of Object
class.
Sometimes they are called literal objects, when created via {}
notation.
Class objects are instances of classes with own defined constructor, properties and methods.
Usually you define them via class
notation.
So, what is the problem?
Sometimes you want to transform plain javascript object to the ES6 classes you have.
For example, if you are loading a json from your backend, some api or from a json file,
and after you JSON.parse
it you have a plain javascript object, not instance of class you have.
For example you have a list of users in your users.json
that you are loading:
1[ 2 { 3 "id": 1, 4 "firstName": "Johny", 5 "lastName": "Cage", 6 "age": 27 7 }, 8 { 9 "id": 2, 10 "firstName": "Ismoil", 11 "lastName": "Somoni", 12 "age": 50 13 }, 14 { 15 "id": 3, 16 "firstName": "Luke", 17 "lastName": "Dacascos", 18 "age": 12 19 } 20]
And you have a User
class:
1export class User { 2 id: number; 3 firstName: string; 4 lastName: string; 5 age: number; 6 7 getName() { 8 return this.firstName + ' ' + this.lastName; 9 } 10 11 isAdult() { 12 return this.age > 36 && this.age < 60; 13 } 14}
You are assuming that you are downloading users of type User
from users.json
file and may want to write
following code:
1fetch('users.json').then((users: User[]) => { 2 // you can use users here, and type hinting also will be available to you, 3 // but users are not actually instances of User class 4 // this means that you can't use methods of User class 5});
In this code you can use users[0].id
, you can also use users[0].firstName
and users[0].lastName
.
However you cannot use users[0].getName()
or users[0].isAdult()
because "users" actually is
array of plain javascript objects, not instances of User object.
You actually lied to compiler when you said that its users: User[]
.
So what to do? How to make a users
array of instances of User
objects instead of plain javascript objects?
Solution is to create new instances of User object and manually copy all properties to new objects.
But things may go wrong very fast once you have a more complex object hierarchy.
Alternatives? Yes, you can use class-transformer. Purpose of this library is to help you to map your plain javascript objects to the instances of classes you have.
This library also great for models exposed in your APIs, because it provides a great tooling to control what your models are exposing in your API. Here is an example how it will look like:
1fetch('users.json').then((users: Object[]) => { 2 const realUsers = plainToInstance(User, users); 3 // now each user in realUsers is an instance of User class 4});
Now you can use users[0].getName()
and users[0].isAdult()
methods.
Install module:
npm install class-transformer --save
reflect-metadata
shim is required, install it too:
npm install reflect-metadata --save
and make sure to import it in a global place, like app.ts:
1import 'reflect-metadata';
ES6 features are used, if you are using old version of node.js you may need to install es6-shim:
npm install es6-shim --save
and import it in a global place like app.ts:
1import 'es6-shim';
Install module:
npm install class-transformer --save
reflect-metadata
shim is required, install it too:
npm install reflect-metadata --save
add <script>
to reflect-metadata in the head of your index.html
:
1<html> 2 <head> 3 <!-- ... --> 4 <script src="node_modules/reflect-metadata/Reflect.js"></script> 5 </head> 6 <!-- ... --> 7</html>
If you are using angular 2 you should already have this shim installed.
If you are using system.js you may want to add this into map
and package
config:
1{ 2 "map": { 3 "class-transformer": "node_modules/class-transformer" 4 }, 5 "packages": { 6 "class-transformer": { "main": "index.js", "defaultExtension": "js" } 7 } 8}
This method transforms a plain javascript object to instance of specific class.
1import { plainToInstance } from 'class-transformer'; 2 3let users = plainToInstance(User, userJson); // to convert user plain object a single user. also supports arrays
This method transforms a plain object into an instance using an already filled Object which is an instance of the target class.
1const defaultUser = new User(); 2defaultUser.role = 'user'; 3 4let mixedUser = plainToClassFromExist(defaultUser, user); // mixed user should have the value role = user when no value is set otherwise.
This method transforms your class object back to plain javascript object, that can be JSON.stringify
later.
1import { instanceToPlain } from 'class-transformer'; 2let photo = instanceToPlain(photo);
This method transforms your class object into a new instance of the class object. This may be treated as deep clone of your objects.
1import { instanceToInstance } from 'class-transformer'; 2let photo = instanceToInstance(photo);
You can also use an ignoreDecorators
option in transformation options to ignore all decorators your classes are using.
You can serialize your model right to json using serialize
method:
1import { serialize } from 'class-transformer'; 2let photo = serialize(photo);
serialize
works with both arrays and non-arrays.
You can deserialize your model from json using the deserialize
method:
1import { deserialize } from 'class-transformer'; 2let photo = deserialize(Photo, photo);
To make deserialization work with arrays, use the deserializeArray
method:
1import { deserializeArray } from 'class-transformer'; 2let photos = deserializeArray(Photo, photos);
The default behaviour of the plainToInstance
method is to set all properties from the plain object,
even those which are not specified in the class.
1import { plainToInstance } from 'class-transformer'; 2 3class User { 4 id: number; 5 firstName: string; 6 lastName: string; 7} 8 9const fromPlainUser = { 10 unkownProp: 'hello there', 11 firstName: 'Umed', 12 lastName: 'Khudoiberdiev', 13}; 14 15console.log(plainToInstance(User, fromPlainUser)); 16 17// User { 18// unkownProp: 'hello there', 19// firstName: 'Umed', 20// lastName: 'Khudoiberdiev', 21// }
If this behaviour does not suit your needs, you can use the excludeExtraneousValues
option
in the plainToInstance
method while exposing all your class properties as a requirement.
1import { Expose, plainToInstance } from 'class-transformer'; 2 3class User { 4 @Expose() id: number; 5 @Expose() firstName: string; 6 @Expose() lastName: string; 7} 8 9const fromPlainUser = { 10 unkownProp: 'hello there', 11 firstName: 'Umed', 12 lastName: 'Khudoiberdiev', 13}; 14 15console.log(plainToInstance(User, fromPlainUser, { excludeExtraneousValues: true })); 16 17// User { 18// id: undefined, 19// firstName: 'Umed', 20// lastName: 'Khudoiberdiev' 21// }
When you are trying to transform objects that have nested objects,
it's required to known what type of object you are trying to transform.
Since Typescript does not have good reflection abilities yet,
we should implicitly specify what type of object each property contain.
This is done using @Type
decorator.
Lets say we have an album with photos. And we are trying to convert album plain object to class object:
1import { Type, plainToInstance } from 'class-transformer'; 2 3export class Album { 4 id: number; 5 6 name: string; 7 8 @Type(() => Photo) 9 photos: Photo[]; 10} 11 12export class Photo { 13 id: number; 14 filename: string; 15} 16 17let album = plainToInstance(Album, albumJson); 18// now album is Album object with Photo objects inside
In case the nested object can be of different types, you can provide an additional options object,
that specifies a discriminator. The discriminator option must define a property
that holds the subtype
name for the object and the possible subTypes
that the nested object can converted to. A sub type
has a value
, that holds the constructor of the Type and the name
, that can match with the property
of the discriminator.
Lets say we have an album that has a top photo. But this photo can be of certain different types.
And we are trying to convert album plain object to class object. The plain object input has to define
the additional property __type
. This property is removed during transformation by default:
JSON input:
1{ 2 "id": 1, 3 "name": "foo", 4 "topPhoto": { 5 "id": 9, 6 "filename": "cool_wale.jpg", 7 "depth": 1245, 8 "__type": "underwater" 9 } 10}
1import { Type, plainToInstance } from 'class-transformer'; 2 3export abstract class Photo { 4 id: number; 5 filename: string; 6} 7 8export class Landscape extends Photo { 9 panorama: boolean; 10} 11 12export class Portrait extends Photo { 13 person: Person; 14} 15 16export class UnderWater extends Photo { 17 depth: number; 18} 19 20export class Album { 21 id: number; 22 name: string; 23 24 @Type(() => Photo, { 25 discriminator: { 26 property: '__type', 27 subTypes: [ 28 { value: Landscape, name: 'landscape' }, 29 { value: Portrait, name: 'portrait' }, 30 { value: UnderWater, name: 'underwater' }, 31 ], 32 }, 33 }) 34 topPhoto: Landscape | Portrait | UnderWater; 35} 36 37let album = plainToInstance(Album, albumJson); 38// now album is Album object with a UnderWater object without `__type` property.
Hint: The same applies for arrays with different sub types. Moreover you can specify keepDiscriminatorProperty: true
in the options to keep the discriminator property also inside your resulting class.
You can expose what your getter or method return by setting an @Expose()
decorator to those getters or methods:
1import { Expose } from 'class-transformer'; 2 3export class User { 4 id: number; 5 firstName: string; 6 lastName: string; 7 password: string; 8 9 @Expose() 10 get name() { 11 return this.firstName + ' ' + this.lastName; 12 } 13 14 @Expose() 15 getFullName() { 16 return this.firstName + ' ' + this.lastName; 17 } 18}
If you want to expose some of the properties with a different name,
you can do that by specifying a name
option to @Expose
decorator:
1import { Expose } from 'class-transformer'; 2 3export class User { 4 @Expose({ name: 'uid' }) 5 id: number; 6 7 firstName: string; 8 9 lastName: string; 10 11 @Expose({ name: 'secretKey' }) 12 password: string; 13 14 @Expose({ name: 'fullName' }) 15 getFullName() { 16 return this.firstName + ' ' + this.lastName; 17 } 18}
Sometimes you want to skip some properties during transformation.
This can be done using @Exclude
decorator:
1import { Exclude } from 'class-transformer'; 2 3export class User { 4 id: number; 5 6 email: string; 7 8 @Exclude() 9 password: string; 10}
Now when you transform a User, the password
property will be skipped and not be included in the transformed result.
You can control on what operation you will exclude a property. Use toClassOnly
or toPlainOnly
options:
1import { Exclude } from 'class-transformer'; 2 3export class User { 4 id: number; 5 6 email: string; 7 8 @Exclude({ toPlainOnly: true }) 9 password: string; 10}
Now password
property will be excluded only during instanceToPlain
operation. Vice versa, use the toClassOnly
option.
You can skip all properties of the class, and expose only those are needed explicitly:
1import { Exclude, Expose } from 'class-transformer'; 2 3@Exclude() 4export class User { 5 @Expose() 6 id: number; 7 8 @Expose() 9 email: string; 10 11 password: string; 12}
Now id
and email
will be exposed, and password will be excluded during transformation.
Alternatively, you can set exclusion strategy during transformation:
1import { instanceToPlain } from 'class-transformer'; 2let photo = instanceToPlain(photo, { strategy: 'excludeAll' });
In this case you don't need to @Exclude()
a whole class.
If you name your private properties with a prefix, lets say with _
,
then you can exclude such properties from transformation too:
1import { instanceToPlain } from 'class-transformer'; 2let photo = instanceToPlain(photo, { excludePrefixes: ['_'] });
This will skip all properties that start with _
prefix.
You can pass any number of prefixes and all properties that begin with these prefixes will be ignored.
For example:
1import { Expose, instanceToPlain } from 'class-transformer'; 2 3export class User { 4 id: number; 5 private _firstName: string; 6 private _lastName: string; 7 _password: string; 8 9 setName(firstName: string, lastName: string) { 10 this._firstName = firstName; 11 this._lastName = lastName; 12 } 13 14 @Expose() 15 get name() { 16 return this._firstName + ' ' + this._lastName; 17 } 18} 19 20const user = new User(); 21user.id = 1; 22user.setName('Johny', 'Cage'); 23user._password = '123'; 24 25const plainUser = instanceToPlain(user, { excludePrefixes: ['_'] }); 26// here plainUser will be equal to 27// { id: 1, name: "Johny Cage" }
You can use groups to control what data will be exposed and what will not be:
1import { Exclude, Expose, instanceToPlain } from 'class-transformer'; 2 3export class User { 4 id: number; 5 6 name: string; 7 8 @Expose({ groups: ['user', 'admin'] }) // this means that this data will be exposed only to users and admins 9 email: string; 10 11 @Expose({ groups: ['user'] }) // this means that this data will be exposed only to users 12 password: string; 13} 14 15let user1 = instanceToPlain(user, { groups: ['user'] }); // will contain id, name, email and password 16let user2 = instanceToPlain(user, { groups: ['admin'] }); // will contain id, name and email
If you are building an API that has different versions, class-transformer has extremely useful tools for that. You can control which properties of your model should be exposed or excluded in what version. Example:
1import { Exclude, Expose, instanceToPlain } from 'class-transformer'; 2 3export class User { 4 id: number; 5 6 name: string; 7 8 @Expose({ since: 0.7, until: 1 }) // this means that this property will be exposed for version starting from 0.7 until 1 9 email: string; 10 11 @Expose({ since: 2.1 }) // this means that this property will be exposed for version starting from 2.1 12 password: string; 13} 14 15let user1 = instanceToPlain(user, { version: 0.5 }); // will contain id and name 16let user2 = instanceToPlain(user, { version: 0.7 }); // will contain id, name and email 17let user3 = instanceToPlain(user, { version: 1 }); // will contain id and name 18let user4 = instanceToPlain(user, { version: 2 }); // will contain id and name 19let user5 = instanceToPlain(user, { version: 2.1 }); // will contain id, name and password
Sometimes you have a Date in your plain javascript object received in a string format.
And you want to create a real javascript Date object from it.
You can do it simply by passing a Date object to the @Type
decorator:
1import { Type } from 'class-transformer'; 2 3export class User { 4 id: number; 5 6 email: string; 7 8 password: string; 9 10 @Type(() => Date) 11 registrationDate: Date; 12}
Same technique can be used with Number
, String
, Boolean
primitive types when you want to convert your values into these types.
When you are using arrays you must provide a type of the object that array contains.
This type, you specify in a @Type()
decorator:
1import { Type } from 'class-transformer'; 2 3export class Photo { 4 id: number; 5 6 name: string; 7 8 @Type(() => Album) 9 albums: Album[]; 10}
You can also use custom array types:
1import { Type } from 'class-transformer'; 2 3export class AlbumCollection extends Array<Album> { 4 // custom array functions ... 5} 6 7export class Photo { 8 id: number; 9 10 name: string; 11 12 @Type(() => Album) 13 albums: AlbumCollection; 14}
Library will handle proper transformation automatically.
ES6 collections Set
and Map
also require the @Type
decorator:
1export class Skill { 2 name: string; 3} 4 5export class Weapon { 6 name: string; 7 range: number; 8} 9 10export class Player { 11 name: string; 12 13 @Type(() => Skill) 14 skills: Set<Skill>; 15 16 @Type(() => Weapon) 17 weapons: Map<string, Weapon>; 18}
You can perform additional data transformation using @Transform
decorator.
For example, you want to make your Date
object to be a moment
object when you are
transforming object from plain to class:
1import { Transform } from 'class-transformer'; 2import * as moment from 'moment'; 3import { Moment } from 'moment'; 4 5export class Photo { 6 id: number; 7 8 @Type(() => Date) 9 @Transform(({ value }) => moment(value), { toClassOnly: true }) 10 date: Moment; 11}
Now when you call plainToInstance
and send a plain representation of the Photo object,
it will convert a date value in your photo object to moment date.
@Transform
decorator also supports groups and versioning.
The @Transform
decorator is given more arguments to let you configure how you want the transformation to be done.
1@Transform(({ value, key, obj, type }) => value)
Argument | Description |
---|---|
value | The property value before the transformation. |
key | The name of the transformed property. |
obj | The transformation source object. |
type | The transformation type. |
options | The options object passed to the transformation method. |
Signature | Example | Description |
---|---|---|
@TransformClassToPlain | @TransformClassToPlain({ groups: ["user"] }) | Transform the method return with instanceToPlain and expose the properties on the class. |
@TransformClassToClass | @TransformClassToClass({ groups: ["user"] }) | Transform the method return with instanceToInstance and expose the properties on the class. |
@TransformPlainToClass | @TransformPlainToClass(User, { groups: ["user"] }) | Transform the method return with plainToInstance and expose the properties on the class. |
The above decorators accept one optional argument: ClassTransformOptions - The transform options like groups, version, name
An example:
1@Exclude() 2class User { 3 id: number; 4 5 @Expose() 6 firstName: string; 7 8 @Expose() 9 lastName: string; 10 11 @Expose({ groups: ['user.email'] }) 12 email: string; 13 14 password: string; 15} 16 17class UserController { 18 @TransformClassToPlain({ groups: ['user.email'] }) 19 getUser() { 20 const user = new User(); 21 user.firstName = 'Snir'; 22 user.lastName = 'Segal'; 23 user.password = 'imnosuperman'; 24 25 return user; 26 } 27} 28 29const controller = new UserController(); 30const user = controller.getUser();
the user
variable will contain only firstName,lastName, email properties because they are
the exposed variables. email property is also exposed because we metioned the group "user.email".
Generics are not supported because TypeScript does not have good reflection abilities yet. Once TypeScript team provide us better runtime type reflection tools, generics will be implemented. There are some tweaks however you can use, that maybe can solve your problem. Checkout this example.
NOTE If you use class-validator together with class-transformer you propably DON'T want to enable this function.
Enables automatic conversion between built-in types based on type information provided by Typescript. Disabled by default.
1import { IsString } from 'class-validator'; 2 3class MyPayload { 4 @IsString() 5 prop: string; 6} 7 8const result1 = plainToInstance(MyPayload, { prop: 1234 }, { enableImplicitConversion: true }); 9const result2 = plainToInstance(MyPayload, { prop: 1234 }, { enableImplicitConversion: false }); 10 11/** 12 * result1 will be `{ prop: "1234" }` - notice how the prop value has been converted to string. 13 * result2 will be `{ prop: 1234 }` - default behaviour 14 */
Circular references are ignored.
For example, if you are transforming class User
that contains property photos
with type of Photo
,
and Photo
contains link user
to its parent User
, then user
will be ignored during transformation.
Circular references are not ignored only during instanceToInstance
operation.
Lets say you want to download users and want them automatically to be mapped to the instances of User
class.
1import { plainToInstance } from 'class-transformer'; 2 3this.http 4 .get('users.json') 5 .map(res => res.json()) 6 .map(res => plainToInstance(User, res as Object[])) 7 .subscribe(users => { 8 // now "users" is type of User[] and each user has getName() and isAdult() methods available 9 console.log(users); 10 });
You can also inject a class ClassTransformer
as a service in providers
, and use its methods.
Example how to use with angular 2 in plunker. Source code is here.
Take a look on samples in ./sample for more examples of usages.
See information about breaking changes and release notes here.
The latest stable version of the package.
Stable Version
1
5.3/10
Summary
Prototype pollution in class-transformer
Affected Versions
< 0.3.1
Patched Versions
0.3.1
Reason
no dangerous workflow patterns detected
Reason
all changesets reviewed
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
7 existing vulnerabilities detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More