首页 > 解决方案 > 带有 type-graphql 的 NullObject 模式

问题描述

在处理继承和 NullObject 模式时,我有一个打字稿问题。

考虑以下:

@ObjectType({ implements: Segment })
export class NullSegment extends Segment {
  public static readonly NAME = 'Other'

  @Field(() => Trait)
  @ManyToOne(() => Trait)
  trait: Trait

  static build(input: NullSegmentInput): NullSegment {
    const out = new this()
    out.name = this.NAME
    out.trait = input.trait
    return out
  }
}

export type NullableSegment<T extends Segment> = T | NullSegment

Segment还有很多其他的实现。

我们在其他地方有:

@ObjectType({ implements: Trait })
export class HealthScoreTrait extends Trait {
  @Field(() => [NullableSegment<HealthscoreSegment>], { nullable: true })
  @OneToMany(() => Segment, (segment) => segment.trait, {
    onDelete: 'CASCADE',
    cascade: true,
    nullable: true
  })
  healthscoreSegments: NullableSegment<HealthscoreSegment>[]
}

当这解析为图表时,我希望可用类型为 HealthScoreSegment | 空段。

但是当我执行以下操作时,@Field() 出现类型错误

像这样在此处输入图像描述

有人知道这里可行的模式吗?我需要为每个 Segment 制作 UnionTypes 对联吗?这似乎真的不干

标签: typescriptgraphqltypegraphql

解决方案


我不确定这是否是最好的答案......但这有效:

const NullableHealthscoreSegment = createUnionType({
  name: "NullableHealthscoreSegment", // the name of the GraphQL union
  types: () => [HealthscoreSegment, NullSegment] as const, // function that returns tuple of object types classes
});

@ObjectType({ implements: Trait })
@ChildEntity()
export class HealthScoreTrait extends Trait {
  @Field(() => [NullableHealthscoreSegment], { nullable: true })
  @OneToMany(() => Segment, (segment) => segment.trait, {
    onDelete: 'CASCADE',
    cascade: true,
    nullable: true,
    lazy: true,
  })
  healthscoreSegments: Lazy<NullableSegment<HealthscoreSegment>[]>
}

推荐阅读