简体   繁体   中英

How to do a Field Resolver for a Union Type in type-graphql

Consider the following

The stack is type-graphql / type-orm / postgres

I am using Single Table Inheritance (STI) and Union Types to represent multiple feed types.

All is working nicely -- until I wanted to add a Field Resolver -- and I could not find a way to get that to work.

It looks like you can not pass an interface type to @Resolver

Some code snippits to illustrate:

The abstract top level entity

@InterfaceType()
@Entity({ orderBy: { createdAt: 'DESC' } })
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export abstract class FeedItem {
  @Field(() => ID)
  @PrimaryGeneratedColumn('uuid')
  id: string

  @Field()
  @Column({ nullable: false })
  type: string

  @Field(() => Customer, { nullable: true })
  @ManyToOne(
    () => Customer,
    customer => customer.feedItems,
    { onDelete: 'CASCADE' }
  )
  customer: Lazy<Customer>

  @Field(() => [FeedItemComment])
  @OneToMany(
    () => FeedItemComment,
    feedItemComment => feedItemComment.feedItem,
    { lazy: true }
  )
  comments: Lazy<FeedItemComment[]>

The resolver

export const FeedResultUnion = createUnionType({
  name: 'FeedItemResult', // the name of the GraphQL union
  types: [AuthoredFeedItem, MilestoneFeedItem, TaskFeedItem, AssessmentFeedItem, WeeklySummaryFeedItem], // array of object types classes


@Resolver(() => FeedItem) // <---- this does not work, nor does FeedItemResult
export class FeedItemResolver {

  // would love to do something like the following, but can't ...
  @Authorized()
  @FieldResolver(() => CommentsResponse)
  async comments(@Root() feedItem: FeedItem) {
    const [feedItems, count] = await getRepository(FeedItemComment).findAndCount({
      where: {
        feedItem,
      },
      order: { createdOn: 'DESC' },
    })

    return {
      items: feedItems,
      count,
    }
  }


}


})

Anyone can point me to a path to victory?!

I also had problems with @FieldResolver() I just made a change in tsconfig.json, I changed "target": "es5" to "target": "es6"

The type-graphql documentation says that you must configure the tsconfig.json for it to work

I hope I have helped

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM