|
| 1 | +# Getting Started |
| 2 | + |
| 3 | +The `class-transformer` package is a zero-dependency utility library helping you to quickly transform class instances to plain objects and vice-versa. |
| 4 | +It works well with the [`class-validator`][class-validator] library. The main features include: |
| 5 | + |
| 6 | +- conditionally transforming object properties |
| 7 | +- excluding specific properties from the transformed object |
| 8 | +- exposing properties under a different name on the transformed object |
| 9 | +- supports both NodeJS and browsers |
| 10 | +- fully three-shakable |
| 11 | +- zero external dependencies |
| 12 | + |
| 13 | +## Installation |
| 14 | + |
| 15 | +To start using class-transformer install the required packages via NPM: |
| 16 | + |
| 17 | +```bash |
| 18 | +npm install class-transformer reflect-metadata |
| 19 | +``` |
| 20 | + |
| 21 | +Import the `reflect-metadata` package at the **first line** of your application: |
| 22 | + |
| 23 | +```ts |
| 24 | +import 'reflect-metadata'; |
| 25 | + |
| 26 | +// Your other imports and initialization code |
| 27 | +// comes here after you imported the reflect-metadata package! |
| 28 | +``` |
| 29 | + |
| 30 | +As the last step, you need to enable emitting decorator metadata in your Typescript config. Add these two lines to your `tsconfig.json` file under the `compilerOptions` key: |
| 31 | + |
| 32 | +```json |
| 33 | +"emitDecoratorMetadata": true, |
| 34 | +"experimentalDecorators": true, |
| 35 | +``` |
| 36 | + |
| 37 | +Now you are ready to use class-transformer with Typescript! |
| 38 | + |
| 39 | +## Basic Usage |
| 40 | + |
| 41 | +The most basic usage is to transform a class to a plain object: |
| 42 | + |
| 43 | +```ts |
| 44 | +import { Expose, Exclude, classToPlain } from 'class-transformer'; |
| 45 | + |
| 46 | +class User { |
| 47 | + /** |
| 48 | + * When transformed to plain the `_id` property will be remapped to `id` |
| 49 | + * in the plain object. |
| 50 | + */ |
| 51 | + @Expose({ name: 'id' }) |
| 52 | + private _id: string; |
| 53 | + |
| 54 | + /** |
| 55 | + * Expose the `name` property as it is in the plain object. |
| 56 | + */ |
| 57 | + @Expose() |
| 58 | + public name: string; |
| 59 | + |
| 60 | + /** |
| 61 | + * Exclude the `passwordHash` so it won't be included in the plain object. |
| 62 | + */ |
| 63 | + @Exclude() |
| 64 | + public passwordHash: string; |
| 65 | +} |
| 66 | + |
| 67 | +const user = getUserMagically(); |
| 68 | +// contains: User { _id: '42', name: 'John Snow', passwordHash: '2f55ce082...' } |
| 69 | + |
| 70 | +const plain = classToPlain(user); |
| 71 | +// contains { id: '42', name: 'John Snow' } |
| 72 | +``` |
| 73 | + |
| 74 | +[class-validator]: https://github.com/typestack/class-validator/ |
0 commit comments