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

2024-01-01

Edit:
我看过这个问题/答案如何从控制器 json 中排除实体字段 https://stackoverflow.com/questions/50360101/how-to-exclude-entity-field-from-returned-by-controller-json-nestjs-typeorm
但是,如下所示 - 这将从所有查询中排除该字段(在尝试处理用户验证时,在不具有 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;
}

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 };
  }
}

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

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

密码包含在响应中

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

@Exclude()
password: string;

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

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

在 Nest.js 中使用以下方法可能吗?ClassSerializerInterceptor?

如果是这样,希望您能指出正确的方向。


您可以跳过属性取决于操作 https://github.com/typestack/class-transformer/blob/develop/README.md#skipping-depend-of-operation。在您的情况下,您将使用:

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

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

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


For the ClassSerializerInterceptor要工作,请确保您的实体首先转换为类。这可以通过使用自动完成ValidationPipe{ 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;
  }

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

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) };
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

序列化:如何排除 json 响应中的实体列,但不排除 Nestjs 中的内部查询 的相关文章

随机推荐