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

fix: Nested objects are empty in some cases when using serialization groups

Open jlefebvre1997 opened this issue 6 months ago • 7 comments

Description

disclaimer : I'm using NestJS but I don't think the issue is related

When trying to serialize an object using instanceToPlain with serialization groups and a nested object, sometimes the nested object is empty

class User {
  @ManyToMany(() => Workspace, (workspace) => workspace.users)
  @Type(() => Workspace)
  @ApiProperty()
  @Expose({ groups: [GROUP_ME, GROUP_ORGANIZATION_USERS] })
  workspaces: Workspace[];
}

class Workspace {
  @PrimaryGeneratedColumn('uuid')
  @Expose({
    groups: [
      GROUP_WORKSPACE,
      GROUP_ORGANIZATION_WORKSPACES,
      GROUP_ORGANIZATION_USERS,
    ],
  })
  id: string;
}

and in the controller :

@UseInterceptors(ClassSerializerInterceptor)
@SerializeOptions({
  groups: [GROUP_ORGANIZATION_USERS],
})
async findUsers(...) {
 // fetch user object in db and return it, so it's an instance of User
}

I skipped a lot of code for the example

Expected behavior

I would expect my User object to be serialized like this :

{
    workspaces: [
        {
            id: '1'
        },
        {
            id: '2'
        }    
    ]
}

Actual behavior

The nested objects are empty :

{
    workspaces: [
        {},
        {}    
    ]
}
```ts

Note that it I don't specify any serialization groups (only using `@Expose()` on my nested object property (workspace.id for example) it works as expected... I'm out of options here, thanks in advance for your time and help 

jlefebvre1997 avatar Aug 20 '24 10:08 jlefebvre1997