【问题标题】:type-graphql entities how to omit fields from JSON.stringify?type-graphql 实体如何从 JSON.stringify 中省略字段?
【发布时间】:2020-05-04 17:14:01
【问题描述】:

我们使用https://github.com/MichalLytek/type-graphql 来定义我们的graphql 模式当我们序列化原始打字稿实体对象时,这不尊重我们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 包含敏感数据。当我们 JSON.stringify 配置文件引用时,我们不希望帐户输出。帐户未使用 @Field 注释,我们预计不会输出。

【问题讨论】:

    标签: node.js typescript graphql apollo-server


    【解决方案1】:

    type-graphql 使用的装饰器仅用于指导 type-graphql 如何将您的类转换为 GraphQL 类型——它们不会以某种方式影响该类的实例如何由像 @987654323 这样的本机函数序列化@。

    在您的架构上下文中,account 永远不会在响应中返回,除非您为它显式创建一个字段,即使您的解析器使用的 Profile 实例具有该属性。这是 GraphQL.js 中字段解析如何工作的一个症状。但是,Profile 实例将始终具有 account 属性,因为这是您在类中定义的。

    从你的问题中不清楚你为什么首先调用stringify,但假设它是在其他一些上下文中使用,比如日志记录,那么你会想要公开你自己的方法来序列化限制实例返回哪些属性。这可以使用lodashpickomit 之类的方式轻松完成。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-18
      • 2019-12-12
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多