nestjs-class-transformer
TypeScript icon, indicating that this package has built-in type declarations

1.0.11 • Public • Published

Nest Logo

Nestjs Injectable class transformer

Community libarary that allows you to use DI to transform your dto.

Table of Contents


How to use

Installation

$ npm install nestjs-class-transformer
Using yarn
$ yarn add nestjs-class-transformer
Using pnpm
$ pnpm install nestjs-class-transformer

Usage

First add the intercepter to the controller

import { TransformerInterceptor } from "nestjs-class-transformer";

@UseInterceptors(TransformerInterceptor)
export class SomeController {}

Remeber, you need to use UseInterceptors on every controller you need it's value to be transformed. You CANNOT use useGlobalInterceptors because each controller must include his own interceptor to be able to use DI correctly.

Then you need to define a transformer.

A transformer is just an injectable class that has a transform as shown below. This class can inject whatever it needs and is accessible in it's module.

import { Transform } from "nestjs-class-transformer";

export class NameTransformer implements Transform {
  constructor(public injectedService: InjectedService) {}

  transform(params: TransformFnParams) {
    return injectedService.formatName(params.value, params.key);
  }
}

Last, in your dto class do the following:

import { Transformer } from "nestjs-class-transformer";
class SomeDto {
  @Transformer(NameTransformer)
  name: string;
}

And that is it, congratulations now you can transform your dtos from your injectable services with ease.

Not Supported

  • it does not work for incoming dto, it only transforms outgoing dto.
  • it does not support any of the TransformOptions object.

Package Sidebar

Install

npm i nestjs-class-transformer

Weekly Downloads

8

Version

1.0.11

License

MIT

Unpacked Size

16.7 kB

Total Files

21

Last publish

Collaborators

  • yamanlakis