Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization: How to exclude Entity columns in json response but not internal queries in Nestjs

Edit:
I have looked at this question/answer How to exclude entity field from controller json
But, as per below - this is excluding that field from all queries (to the porint where when trying to process user validation, the password field is excluded using the findOne repository query on a route/controller method that does not have ClassSerializerInterceptor

I have an entity within nest.js / typeorm; I am trying to exclude the password field from the returned json, but not exclude the password field from any repository queries within my service. For example:

user.entity.ts:

import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, 
UpdateDateColumn, ManyToOne } from 'typeorm';
import { Exclude } from 'class-transformer';
import { Account } from '../accounts/account.entity';

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column({
    unique: true,
  })
  email: string;

 @Column()
 password: string;
}

auth.controller.ts:

import { Controller, Post, Body, Request, Req, Get, UseInterceptors, ClassSerializerInterceptor, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { IUserRequest } from '../../interfaces/user-request.interface';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('/login')
  async login(@Request() req: Request) {
    const user = await this.authService.checkCredentials(req.body);
    return this.authService.logUserIn(user.id);
  }

  @Get('/profile')
  @UseGuards(AuthGuard())
  @UseInterceptors(ClassSerializerInterceptor)
  async profile(@Request() req: IUserRequest) {
    const profile = await this.authService.getLoggedInProfile(req.user.id);
    return { profile };
  }
}

If I add Exclude() to password like so

@Exclude()
@Column()
password: string;

the password is included in the response

If I remove the Column() from password,

@Exclude()
password: string;

Password is excluded from response and all internal queries such as:

const user = await this.userRepository.findOne({ where: { id }, relations: ['account']});

Is this possible in nest.js using the ClassSerializerInterceptor?

If so, would appreciate a pointer in the right direction.

like image 522
RWest Avatar asked Jan 23 '19 13:01

RWest


2 Answers

You can skip properties depending on the operation. In your case, you would use:

@Column()
@Exclude({ toPlainOnly: true })
password: string;

This means, that password is only skipped when a class is transformed to json (when you send a response) and not when json is transformed to a class (when you get a request).

Then add the @UseInterceptors(ClassSerializerInterceptor) to your controller or a controller method. This will automatically transform an entity class to json, when you return it.


For the ClassSerializerInterceptor to work, make sure that your entity was transformed to a class first. This can be automatically done by using the ValidationPipe with the { transform: true} option or by returning an entity from a repository (database). Also, you have to return the entity itself:

@Post()
@UseInterceptors(ClassSerializerInterceptor)
addUser(@Body(new ValidationPipe({transform: true})) user: User) {
  // Logs user with password
  console.log(user);
  // Returns user as JSON without password
  return user;
  }

Otherwise, you have to transform it manually:

async profile(@Request() req: IUserRequest) {
  // Profile comes from the database so it will be an entity class instance already
  const profile = await this.authService.getLoggedInProfile(req.user.id);
  // Since we are not returning the entity directly, we have to transform it manually
  return { profile: plainToClass(profile) };
}
like image 120
Kim Kern Avatar answered Nov 12 '22 02:11

Kim Kern


Would advice also looking at TypeOrm hidden-columns Here you have @Column({select: false}) on your password column , all requests using a standard find or query will exclude the password column.

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {

@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@Column({select: false})
password: string;
}

Then during validations/cases where you need the password you do

const users = await connection.getRepository(User)
.createQueryBuilder()
.select("user.id", "id")
.addSelect("user.password")
.getMany();
like image 23
Nelson Bwogora Avatar answered Nov 12 '22 01:11

Nelson Bwogora