javascript - 序列化 : How to exclude Entity columns in json response but not internal queries in Nestjs

标签 javascript node.js typescript nestjs class-transformer

编辑:
我看过这个问题/答案 How to exclude entity field from controller json
但是,如下所示 - 这是从所有查询中排除该字段(在尝试处理用户验证时,密码字段被排除在没有 ClassSerializerInterceptor 的路由/ Controller 方法上使用 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;

密码被排除在响应所有内部查询之外,例如:

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

这在使用 ClassSerializerInterceptor 的 nest.js 中是否可行?

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

最佳答案

您可以跳过属性 depending on the operation .在您的情况下,您将使用:

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

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

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


要使 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) };
}

关于javascript - 序列化 : How to exclude Entity columns in json response but not internal queries in Nestjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54328563/

相关文章:

node.js - 在 Travis 构建/测试成功后,如何将 Node.js 应用程序部署到私有(private)服务器?

asp.net - 使用 Visual Studio 2015 在 gulp 中检测发布/调试

javascript - 所需的脚本可以停止其父脚本的执行吗?

javascript - 为什么 SoundCloud API 看起来有缺陷?

css - 覆盖 Twitter Bootstrap 不起作用

javascript - 禁用 Angular react 形式的字段

node.js - typescript jwt.verify 无法访问数据

javascript - Jquery 或 Javascript 重定向到 Controller /操作

javascript - 如何在 Bokeh 中创建加载指示器?

javascript - facebook graph api node.js 无效 appsecret_proof