基于父字段的graphql条件子查询

graphql conditional subquery based on parent field

当您的子查询需要父查询中的某些字段来解析时,该方法是什么?

在我的情况下 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=;`, [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)
}

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

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

I was thinking that resolver will drop additional props internally.

稍后会从 'final' 响应 [object/tree] 中删除。