【问题标题】:Nestjs GraphQL schema first - how to add the property resolvers for a union type?Nestjs GraphQL 架构首先 - 如何为联合类型添加属性解析器?
【发布时间】:2020-05-06 14:03:20
【问题描述】:

我需要一些帮助,我无法完成这项工作。

我首先使用带有 GraphQL 的 NestJs - 架构。

我有以下架构:

type Small {
    id: Int
    name: String
    color: String
}

type Big {
    id: Int
    name: String
    size: Int
}

type Huge {
    id: Int
    name: String
    engine: Int
}

type Cars {
    id: Int
    name: String
    type: Types
}

union Types = Small | Big | Huge

type Query {
    car(id: ID!): Cars
}

您能告诉我如何为 type 字段(即 Types 类型)创建解析器吗?

【问题讨论】:

    标签: graphql union nestjs


    【解决方案1】:

    最后我想通了。问题是添加解析类型函数来确定要返回的对象类型。在一些输/赢的战斗之后,我发现您需要为联合类型类创建一个单独的解析器,并在另一个解析器中为具有联合类型的字段创建一个。所以考虑到我上面的例子,我需要: 1.为Types类型创建解析器:

    @Resolver('Types')
    export class TypesResolver {
        @ResolveProperty()
        __resolveType(obj) {
            if (obj instanceof Small) {
                return 'Small';
            }
            if (obj instanceof Big) {
                return 'Big';
            }
            return null;
        }
    }
    
    1. 解析 Cars 解析器中使用的具有 Types 类型的属性,并返回所需的对象:
    @ResolveProperty('type')
    __resolveType(obj): any {
        if (obj.color) {
            return this.smallService.getByColor(obj.color);
        }
        if (obj.size) {
            return this.bigService.getBySize(obj.size);
        }
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2018-10-03
      • 2021-01-07
      • 2020-08-31
      • 2019-07-01
      • 1970-01-01
      • 2020-04-05
      • 2020-12-30
      • 2019-07-20
      相关资源
      最近更新 更多