【发布时间】: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 谢谢,我在想解析器会在内部丢弃额外的道具。请回答,以便我接受。