【问题标题】:graphql conditional subquery based on parent field基于父字段的graphql条件子查询
【发布时间】:2020-08-15 05:42:11
【问题描述】:

当您的子查询需要来自父级的某些字段来解析时,有什么方法?

在我的情况下,所有者解析器需要来自父级的 owner_id 字段,但如果用户不请求它,我该怎么办?

当owner_id 不在请求中时,我应该以某种方式强制获取owner_id 字段还是跳过获取所有者?

有问题的查询:

 project(projectId: $projectId) {
      name
      owner_id <--- what if user didn't fetch this
      owner {
        nickname
      }
    }

Graphql 类型:

  type Project {
    id: ID!
    name: String!
    owner_id: String!
    owner: User!
  }

和解析器:

export const project = async (_, args, ___, info) => {
  return await getProjectById(args.projectId, getAstFields(info))
}

export default {
  async owner(parent, __, ___, info) {
    return await getUserById(parent.owner_id, getAstFields(info))
  },
}

无关紧要的辅助函数:

export const getUserById = async (userId: string, fields: string[]) => {
  const [owner] = await query<any>(`SELECT ${fields.join()} FROM users WHERE id=$1;`, [userId])

  return owner
}

export const getAstFields = (info: GraphQLResolveInfo): string[] => {
  const { fields } = simplify(parse(info) as any, info.returnType) as { fields: { [key: string]: { name: string } } }

  return Object.entries(fields).map(([, v]) => v.name)
}

【问题讨论】:

  • 总是阅读owner_id?将其附加到getAstFields() 结果
  • @xadm getAstFields 是获取 sql 查询请求字段的函数,我不知道你是什么意思...
  • 修改它以接受附加参数,即使未在查询中定义/请求,也始终返回owner_id(在子集中)
  • @xadm 谢谢,我在想解析器会在内部丢弃额外的道具。请回答,以便我接受。

标签: graphql apollo


【解决方案1】:

您始终可以在project 类型解析器中读取owner_id。

在这种情况下 ... 修改 getAstFields 函数以接受附加参数 f.e.一组始终需要的属性。这样您就可以将owner_id 附加到查询中请求的字段(在info 中定义)。

我在想解析器会在内部丢弃额外的道具。

稍后将从“最终”响应 [object/tree] 中删除。

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2020-02-28
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多