Skip to content

feature: dependecy injection #461

Open
@Arnaud-Dev-Nodejs

Description

@Arnaud-Dev-Nodejs

Description

To follow the previous issue : #153
Actually using NestJS, I create a new TransformModifier like this :

import { TransformOptions } from "class-transformer";
import { defaultMetadataStorage } from "class-transformer/storage";

export function Deserialize(
  separator: string | RegExp = " ",
  options: TransformOptions = {}
): PropertyDecorator {
  const transformFn = (value: any, obj: any) => String(value).split(separator);

  return function (target: any, propertyName: string | Symbol): void {
    defaultMetadataStorage.addTransformMetadata({
      target: target.constructor,
      propertyName: propertyName as string,
      transformFn,
      options
    });
  };
}

but I require to inject ConfigService in it to get the 'separator' input to do something like that

export function Deserialize(
  appType: string | RegExp = " ",
  options: TransformOptions = {}
): PropertyDecorator {
  const separator = this.config.get<AppConfig>("MyClientConfig").splitSeperator;
  const transformFn = (value: any, obj: any) => String(value).split(separator);

  return function (target: any, propertyName: string | Symbol): void {
    defaultMetadataStorage.addTransformMetadata({
      target: target.constructor,
      propertyName: propertyName as string,
      transformFn,
      options
    });
  };
}

the problem is at the moment of the initialization of the Decorator, the data of the config are not up. So I have to inject it.

Proposed solution

class-validator offers a solution ; they add a "useContainer" functionnality like this :

 useContainer(app.select(AppModule), { fallbackOnErrors: true });

and allow in class to do that :

  constructor(@Inject('ConfigService') public readonly config: ConfigService) {
    super();
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions