Search code examples
javascriptnode.jstypescriptnestjsclass-transformer

NestJS strategy for excluding fields for different user roles?


Let's say I have a base entity, ShopsEntity, that has a bunch of fields along with a secret property:

@ObjectType()
class ShopsEntity {

   @Field()
   name: string;

   @Field()
   rating: string;

   @Field()
   secret: string;
}

I don't want the secret property to be serialised unless a user has a certain role defined through Nest Access Control (That module only allows for RoleGuards to be placed on the resolvers themselves, meaning I would need different routes per role).

So, following a request to the same endpoint with differing levels of authentication, an Admin would get:

{
  "name": "name",
  "rating": "rating",
  "secret": "secret"
}

and a regular querying user would get:

{
  "name": "name",
  "rating": "rating"
}

Is there a declarative way in which I can do property-level security here, or is the best solution having separate DTO's for each level of security?


Solution

  • With class-transformer, you can use the groups property to expose properties only for certain groups/roles:

    import {Exclude, Expose} from "class-transformer";
    
    @Exclude()
    export class User {
    
        @Expose({ groups: ["admin"] })
        secret: string;
    }
    

    On how to use the ClassSerializerInterceptor with groups, see the following answer.