type-graphql 实体如何从 JSON.stringify 中省略字段?
type-graphql entities how to omit fields from JSON.stringify?
我们正在使用 https://github.com/MichalLytek/type-graphql 来定义我们的 graphql 模式 当我们序列化原始打字稿实体对象时,这不尊重我们 GQL 实体中的各种字段注释,最终会泄漏不需要的数据。配置文件实体下方的示例 class
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
注释,我们预计它不会被输出。
type-graphql
使用的装饰器仅用于指示 type-graphql
如何将您的 class 转换为 GraphQL 类型——它们不会以某种方式影响class 由像 JSON.stringify
这样的本机函数序列化。
在您的架构上下文中,除非您明确为其创建一个字段,否则 account
永远不会在响应中返回,即使您的解析器使用的 Profile
实例具有属性。这是字段解析如何在 GraphQL.js 中工作的症状。但是,Profile
实例将始终有一个 account
属性,因为这是您定义的 class.
的一部分
从你的问题中不清楚你为什么首先调用 stringify
,但假设它是在其他一些上下文中使用,比如日志记录,那么你会想要公开你自己的序列化方法限制返回哪些属性的实例。这可以使用 lodash
的 pick
或 omit
.
之类的东西轻松完成
serialize () {
return _.omit(this, ['account'])
}
我们正在使用 https://github.com/MichalLytek/type-graphql 来定义我们的 graphql 模式 当我们序列化原始打字稿实体对象时,这不尊重我们 GQL 实体中的各种字段注释,最终会泄漏不需要的数据。配置文件实体下方的示例 class
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
注释,我们预计它不会被输出。
type-graphql
使用的装饰器仅用于指示 type-graphql
如何将您的 class 转换为 GraphQL 类型——它们不会以某种方式影响class 由像 JSON.stringify
这样的本机函数序列化。
在您的架构上下文中,除非您明确为其创建一个字段,否则 account
永远不会在响应中返回,即使您的解析器使用的 Profile
实例具有属性。这是字段解析如何在 GraphQL.js 中工作的症状。但是,Profile
实例将始终有一个 account
属性,因为这是您定义的 class.
从你的问题中不清楚你为什么首先调用 stringify
,但假设它是在其他一些上下文中使用,比如日志记录,那么你会想要公开你自己的序列化方法限制返回哪些属性的实例。这可以使用 lodash
的 pick
或 omit
.
serialize () {
return _.omit(this, ['account'])
}