代码之家  ›  专栏  ›  技术社区  ›  Ericgit Praneeth Vithanage

在graphql中使用Union type | |返回Union type为的列表时,应为Iterable,但未为字段找到Iterable

  •  0
  • Ericgit Praneeth Vithanage  · 技术社区  · 5 年前

    当我试图返回时,我正在使用Apollo服务器返回项目数据列表(数组) Error 联合类型它显示此错误:

      "errors": [
        {
          "message": "Expected Iterable, but did not find one for field \"Query.getReports\".",
    

    我的模式:

    type Query {
        getReports(id: ID!, patient_id: Int): [getReportUnion]!
      }
    
      union getReportUnion = Error | getReportResult 
    
      type getReportResult {
        id: ID!
        patient_id: Int!
      }
    
      type Error {
        error: Boolean!
        message: String!
      }
    

    我的解析器:

      getReports: async (parent: any, args: any, context: any, info: any) => {
        /**
         * Simplify
         */
        const { id, patient_id } = args;
        const { isAuth, userId } = context.Auth;
        
        /**
         * Authenticating user is logged in
         */
        if (!!!isAuth || userId !== id)
          return { __typename: "Error", error: err, message: mesg };
    
       // if a user is logged in then it works well
      }
    

    我的问题是:

    query {
      getReports(id: "5f449b73e2ccbc43aa5204d88", patient_id: 0) {
      __typename
        ... on getReportResult {
                patient_id
          date
        }
        ... on Error {
          error
          message
        }
      }
    }
    

    问题是当我试图通过错误的考试时 id 争论或 jwt token ,它显示错误。如果每 身份证件 jwt令牌 由于标题是正确的,那么它的工作就像魅力。所以问题是什么时候 身份证件 jwt令牌 是错的,我想展示一下 错误 键入以通知用户有问题!

    我已经试过了,但没有成功:

     type Query {
            getReports(id: ID!, patient_id: Int): getReportUnion!
          }
        
          union getReportUnion = Error | [getReportResult] 
    

    它显示了另一个错误,是否有任何解决方法来消除此错误并显示 错误 .你的回答对我们很有价值!

    1 回复  |  直到 5 年前
        1
  •  1
  •   Daniel Rearden    5 年前

    如果字段的类型是列表,则解析程序必须返回 iterable (即数组)或解析为一的承诺。

    字段的类型是列表( [getReportUnion] )。但是,在解析程序中,您将返回一个对象文字:

    return { __typename: "Error", error: err, message: mesg }
    

    您应该返回一个数组:

    return [{ __typename: "Error", error: err, message: mesg }]
    

    你没办法回来了 任何一个 名单 getReportResult 对象或单个 Error 对象要做到这一点,唯一的办法就是包装 getReportResult 使用另一种类型,并在工会内部使用该类型。

    type Query {
        getReports(id: ID!, patient_id: Int): GetReportPayload!
      }
    
      union GetReportPayload = Error | GetReportResults
    
      type GetReportResults {
        results: [Report!]!
      }
    
      type Report {
        id: ID!
        patientId: Int!
      }
    
      type Error {
        error: Boolean!
        message: String!
      }
    
    推荐文章