网站搜索

node.js - type-graphql 实体如何在 JSON.stringify 中省略字段?


我们正在使用 https://github.com/MichalLytek/type-graphql 来定义我们的 GraphQL 模式。当我们序列化原始 TypeScript 实体对象时,这不会遵循我们 GQL 实体中的各种字段注解,并且最终会泄露不需要的数据。下面是一个 Profile 实体类的示例

import { Field, Int, ObjectType } from 'type-graphql'
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm'
import { Account } from '../account/account.entity'

export class Profile {
  @Field()
  @Column({ unique: true })
  public username: string

  @Field()
  @Column()
  public name: string

  // Relations

  @Column()
  public accountId: string

  @ManyToOne(type => Account, account => account.profiles, { eager: true })
  public account: Account
}

account 包含敏感数据。当我们对 Profile 引用进行 JSON.stringify 时,不希望输出 account。Account 没有用 @Field 注解,我们期望它不会被输出。

答案#1

type-graphql使用的装饰器只是为了指示type-graphql如何将你的类转换为GraphQL类型——它们不会以任何方式影响类的实例如何被原生函数如JSON.stringify序列化。

在你的模式上下文中,除非你明确为其创建字段,否则 account 永远不会在响应中返回,即使你的解析器使用的 Profile 实例具有该属性。这是 GraphQL.js 字段解析工作方式的一个表现。然而,Profile 实例将始终具有一个 account 属性,因为这是你在类中定义的一部分。

从你的问题中不清楚为什么你一开始要调用stringify,但假设这是为了在其他上下文中使用,比如日志记录,那么你需要公开你自己的方法来序列化该实例,并限制返回的属性。这可以很容易地使用像lodash的pick或omit来完成。

serialize () {
  return _.omit(this, ['account'])
}