【问题标题】:NullObject pattern with type-graphql带有 type-graphql 的 NullObject 模式
【发布时间】:2020-11-07 18:32:08
【问题描述】:

在处理继承和 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 | NullSegment。

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

喜欢

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

【问题讨论】:

标签: typescript graphql typegraphql


【解决方案1】:

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

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>[]>
}

【讨论】:

  • 在 Type-Graphql 的 Gitter 上问过,但我也会在这里问。如果我可以问,您如何在客户端上使用它?或者更确切地说,与只有 null 可用时相比,您会做哪些不同的事情?
  • 我只是为了持久化动态过滤。例如,查找所有没有健康评分段的客户
猜你喜欢
  • 2020-08-19
  • 2012-11-17
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 2021-01-01
  • 2021-02-13
  • 2023-03-10
  • 2018-03-15
相关资源
最近更新 更多