【问题标题】:TypeGraphQL_How to avoid creating fields that have not been inputted类型 GraphQL 如何避免创建未输入的字段
【发布时间】:2021-12-17 13:14:17
【问题描述】:
@Resolver()
export class NameCardCreateResolver {
  @Mutation(() => BaseMutationResponse)
  async namecardCreate(
    @Arg("chosenSNSUrls", () => SNSInput)
    { facebook, twitter, instagram, blog, youtube }: SNSInput,
    @Arg("owner", () => NameCardOwner)
    { ownerEmail }: NameCardOwner
  ): Promise<BaseMutationResponse> {
    const response = new BaseMutationResponse();
    try {
      await NameCardModel.create({
        sns: {
          facebook,
          twitter,
          instagram,
          blog,
          youtube
        },
        owner: {
          email: ownerEmail,
        },

还有SNSINPUT类型,,

@InputType()
export class SNSInput {
  @Field({ nullable: true, defaultValue: null })
  facebook?: string;

  @Field({ nullable: true, defaultValue: null })
  instagram?: string;

  @Field({ nullable: true, defaultValue: null })
  youtube?: string;

  @Field({ nullable: true, defaultValue: null })
  blog?: string;

  @Field({ nullable: true, defaultValue: null })
  twitter?: string;
}

它运作良好,但它是在我的 MongoDB 领域中创建的。

enter image description here

如何防止创建不必要的 null 处理 sns 字段?

【问题讨论】:

    标签: typescript mongodb graphql resolver typegraphql


    【解决方案1】:

    如果您不想将字段保存到 MongoDB,请将其值设置为 undefined(而不是 null)。这应该从文档中完全省略该字段。

    您可能必须从 typegraphql 注释中删除 defaultValue: null,因为这可能会将其默认设置为 null

    @InputType()
    export class SNSInput {
      @Field({ nullable: true })
      facebook?: string;
    
      @Field({ nullable: true })
      instagram?: string;
    
      @Field({ nullable: true })
      youtube?: string;
    
      @Field({ nullable: true })
      blog?: string;
    
      @Field({ nullable: true })
      twitter?: string;
    }
    

    或者,如果您想保留输入中的 null 值,则必须使用 undefined 显式覆盖它们或使用 delete 完全删除它们。

    【讨论】:

      猜你喜欢
      • 2018-06-24
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2015-10-28
      • 2019-07-23
      • 2013-05-17
      • 2016-08-30
      相关资源
      最近更新 更多