【问题标题】:setup multiple return types for the NestJs GraphQL Query decorator为 NestJs GraphQL 查询装饰器设置多种返回类型
【发布时间】:2020-05-27 21:33:21
【问题描述】:

我想使用 NestJs 创建一个 GraphQL API。据我了解,我不会再为无效请求抛出 HTTP 异常。因此,我认为我必须创建自己的“错误代码”,然后才能将其发回给客户。所以给出这个基本的例子

@ObjectType()
export class ErrorResponse {
  @Field()
  message: string;
}

我有一个服务函数通过用户 ID 返回用户,并且我扩展了返回类型以在请求无效时返回错误对象。

  public async getUserById(id: number): Promise<ErrorResponse | User> {
    const user: User = await this.usersRepository.findOne(id);

    if (!user) {
      const errorResponse: ErrorResponse = new ErrorResponse();
      errorResponse.message = `User with ID ${id} does not exist`;
      return errorResponse;
    }

    return user;
  }

解析器最初类似于

  @Query(() => User)
  public async user(@Args('id') id: number): Promise<ErrorResponse | User> {
    return this.usersService.getUserById(id);
  }

但如上所述,如果id 不存在,也可以返回ErrorResponse。如何设计 Query 装饰器以提供多种返回类型?

@Query(() => ErrorResponse | User)

不会成功并显示此错误

算术运算的左边必须是'any'类型, 'number'、'bigint' 或枚举类型.ts(2362)

【问题讨论】:

    标签: graphql nestjs typegraphql


    【解决方案1】:

    这是我针对类似情况提出的解决方案。 GraphQL 期望单个返回 ObjectType。 首先我创建了一个通用对象

    @ObjectType()
    export class MutationResult {
      @Field({ nullable: true })
      success?: boolean;
    
      @Field({ nullable: true })
      error?: boolean;
    }
    

    然后在用户模块中,我创建了 2 个对象类型 - UserUserResponse。在 UserResponse 上,我扩展了常见的 MutationResult 对象

    @ObjectType()
    export class User {
      @Field(type => ID)
      id: string;
    
      @Field()
      name: string;
    }
    
    @ObjectType()
    export class UserResponse extends MutationResult {
      @Field()
      result: User;
    }
    

    现在在查询中你可以这样做

    mutation {
      addUser(name: "Test") {
        success,
        error,
        result {
          name
        }
      }
    }
    

    【讨论】:

    • 嗯,如果只有一种类型是可能的,那么这似乎就是答案
    【解决方案2】:

    如果ErrorResponseUser 都是@ObjectType,您只需使用createUnionType 将它们“合并”在一起。

    https://docs.nestjs.com/graphql/unions-and-enums

    【讨论】:

      【解决方案3】:

      Michal 的回答似乎有效,但链接正在重定向到一些垃圾邮件。下面的链接是nestjs的官方文档: https://docs.nestjs.com/graphql/unions-and-enums

      【讨论】:

      • 我已经编辑了 Michal 的答案,你现在可以删除你的。感谢您提供更新的链接。
      猜你喜欢
      • 2019-07-30
      • 2014-03-18
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2018-08-02
      • 2014-04-08
      • 2021-06-24
      相关资源
      最近更新 更多