class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

feat: allow defining different groups for toPlain and toClass operations

Open NoNameProvided opened this issue 4 years ago • 4 comments

Description

Note: Requested by @slavafomin, this issue is created from #57.

Users should be able to allow defining different groups for plainToClass and classToPlain. Example:

@Exclude()
class User {
  @Expose({ toClassOnly: true, groups: ["create", "update"] })
  @Expose({ toPlainOnly: true })
  public email?: string;

  @Expose({ toClassOnly: true, groups: ["create", "update"] })
  @Expose({ toPlainOnly: true })
  public firstName?: string;

  @Expose({ toClassOnly: true, groups: ["create"] })
  @Expose({ toPlainOnly: true })
  public password?: string;
}
const instance = plainToClass(User, {
  email: "[email protected]",
  firstName: "John",
  password: "12345"
}, { groups: ["update"] });

/* Instance should be { firstName: 'John', email: '[email protected]'  }*/
// parameter is a User instance
const json= classToPlain(<User>{
  email: "[email protected]",
  firstName: "John",
  password: "12345"
});

/* JSON should be { firstName: 'John', password: '12345', email: '[email protected]'  }*/

We need to discuss what is the motivation behind this and can we achieve this with the current toolset or not.

NoNameProvided avatar Jul 29 '20 18:07 NoNameProvided

is this still in process?

exejutable avatar Dec 28 '20 16:12 exejutable

We have come across a use case where this would be extremely helpful. In our situation, we needed to set the "name" attribute differently based on whether we were going classToPlain or plainToClass.

AdrianMcGrathFlailsoft avatar Jul 08 '21 20:07 AdrianMcGrathFlailsoft

Any news? We also came across some use cases for this. Not only multiple @Expose but also multiple @Transform would be really nice to handle one single class that maps to multiple sources and targets. Right now we have to duplicate the class if we want to map to multiple sources/targets.

CodingMeSwiftly avatar Sep 11 '21 17:09 CodingMeSwiftly

Any updates on this? Would be super helpful for reusing classes efficiently with both functions. Another example, fetching from a database and having the document model transformed with all specified properties exposed, but when serializing for a user it makes use of the groups.

I guess you could just have a single group you apply to everything when fetching from the database, but it would be nice to have this option as well.

miapolis avatar Apr 24 '22 21:04 miapolis