显示列表数据时返回Union Graphql类型的自定义错误|在graphql中返回具有联合类型的列表

时间:2020-08-30 12:24:52

标签: express graphql apollo apollo-server

当我尝试返回SRC_DIR := ../../src/hello ASM_TARGETS := hellomain.s sayhello.s .PHONY: all clean all: $(ASM_TARGETS) # build .s file from .c file placed in a specified source dir %.s: $(SRC_DIR)/%.c gcc -S $^ -o $@ clean: rm -f $(ASM_TARGETS) 联合类型时,我正在使用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 tokenid作为标题都是正确的,则它就像魅力。所以问题是当jwt tokenid错误时,我想显示jwt token类型来通知用户某些问题!

我已经尝试过但不能正常工作:

Error

它显示了另一个错误,是否有任何解决方法可以消除此错误并显示 type Query { getReports(id: ID!, patient_id: Int): getReportUnion! } union getReportUnion = Error | [getReportResult] 。您的回答对我们很有价值!

1 个答案:

答案 0 :(得分:1)

如果您的字段类型为列表,则您的解析器必须返回iterable(即数组)或解析为一个的Promise。

您的字段的类型为列表([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!
  }