序列化:如何排除json响应中的Entity列,但不排除Nestjs中的内部查询

RWe*_*est 3 javascript node.js typescript nestjs class-transformer

编辑
我已经看过这个问题/答案如何从控制器json中排除实体字段
但是,如下所示-这是从所有查询中排除该字段(到porint,在尝试处理用户验证时,使用在不具有ClassSerializerInterceptor的路由/控制器方法上的findOne存储库查询

我在nest.js / typeorm中有一个实体;我试图从返回的json中排除密码字段,但不从我的服务中的任何存储库查询中排除密码字段。例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

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 };
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我这样添加Exclude()密码

@Exclude()
@Column()
password: string;
Run Code Online (Sandbox Code Playgroud)

密码包含在响应中

如果我Column()从密码中删除,

@Exclude()
password: string;
Run Code Online (Sandbox Code Playgroud)

密码不包括在响应所有内部查询中,例如:

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

是否可以在nest.js中使用ClassSerializerInterceptor

如果是这样,不胜感激正确方向的指针。

Kim*_*ern 6

您可以根据操作跳过属性。在您的情况下,您将使用:

@Column()
@Exclude({ toPlainOnly: true })
password: string;
Run Code Online (Sandbox Code Playgroud)

这意味着,仅当将类转换为json时(发送响应时)才跳过该密码,而当将json转换为类时(收到请求时)则不会跳过该密码。

然后将添加@UseInterceptors(ClassSerializerInterceptor)到您的控制器或控制器方法。返回实体类时,它将自动将其转换为json。


为了使ClassSerializerInterceptor正常工作,请确保首先将您的实体转换为类。可以通过将ValidationPipewith与{ transform: true}选项一起使用或从存储库(数据库)返回实体来自动完成此操作。另外,您必须返回实体本身:

@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;
  }
Run Code Online (Sandbox Code Playgroud)

否则,您必须手动对其进行转换:

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) };
}
Run Code Online (Sandbox Code Playgroud)