簡體   English   中英

type-graphql 使字段解析器異常

[英]type-graphql make exception from Field Resolver

例如,我有一個以下實體和解析器,

    export class SampleA extends BaseEntity {
      @Field()
      @PrimaryGeneratedColumn()
      id!: number;
    
      @Field()
      @Column()
      title!: string
    
      @Field()
      @Column()
      answer!: string;
     }


    @Resolver(SampleA)
    export class SampleAResolver {

        @FieldResolver(() => String)
        async answer(@Root() sampleA: SampleA, @Ctx() {req}: MyContext) {
            const msg = "answer is not public";
            if(!req.session.userId) return msg;
            return sampleA.answer;
        }
    }

結果很好。 只要不滿足條件,整個應用程序的answer字段將始終為“答案不公開”。 但是,如果有時我想破例,

例如,如果我有以下

@ObjectType()
class ExceptedResponse {
    @Field(() => String, {nullable: true})
    errors?: string;
    @Field(() => SampleA, {nullable: true})
    result?: SampleA;
}

當我嘗試返回SampleA ExceptedResponse將始終被answer @FieldResolver()過濾,因此我無法得到真正的answer

所以我想知道我是否可以在不手動重新創建一個全新字段的情況下將其排除在外

@ObjectType()
class ExceptedResponse {
    @Field(() => String, {nullable: true})
    errors?: string;
    @Field(() => {id: Number, title: String, answer: String }, {nullable: true})
    result?: {id: number, title: string, answer: string };
}

//then I just manually assign each value inside my graphql method

或者理想情況下,如果我可以使SpecialSampleASampleA擴展而不受此限制。

經過一些隨機測試,似乎實現我的目標非常簡單。 只需簡單地創建一個新的 class,然后將SampleA結果分配給它。 它由type-graphql自動處理並轉義解析字段檢查,因為Class已更改;

@ObjectType()
class ExceptedSampleA {
  @Field()
  inspiration: string;
  @Field()
  answer: string;
}
//inside response
    @Field(() => ExceptedSampleA, {nullable: true})
    result?: ExceptedSampleA;

//inside graphql method like Mutation() then return response
   const sampleA = SampleA.findOne();
   return { result: sampleA, error: someError }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM