gpt4 book ai didi

graphql:按嵌套字段排序

转载 作者:行者123 更新时间:2023-12-02 10:41:13 26 4
gpt4 key购买 nike

假设我有 2 张 table :
- 用户(ID、姓名、帖子)
- 帖子(id、消息、用户)

如何按用户名(desc)获取前 10 个帖子订单?

这是我的架构的样子:

var PostType = new GraphQLObjectType({
name: "Post",
fields: () => ({
id: { type: GraphQLInt },
message: { type: GraphQLString },
user: {
type: UserType,
args: {
orderBy: { type: sortType }
},
resolve(parent, args) {
console.info("Post resolve called.");
return userMap[parent.user];
}
}
})
});

var RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
allPosts: {
type: new GraphQLList(PostType),
resolve(parentValue, args) {
console.info("allPosts resolve called.");
return postData;
}
}
}
});

和查询:

{
allPosts {
message
user (orderBy: {field: "name", direction: ASC}) {
name
}
}
}

有什么方法可以在 allPosts 解析器函数之前调用用户解析器函数吗?因为,我试图获取按名称排序的 10 个用户,然后将帖子 id 传递给 allPosts 解析器。

最佳答案

GraphQL 字段以自上而下的方式解析。这意味着首先解析 allPosts,然后解析 messageuser 字段(同时),最后解析 name 字段。这是必须发生的,因为“父”或根字段的解析值决定了随后作为根值传递给其子字段的解析器的值。信息从“较高”解析器流向“较低”解析器,但反之则不然。

这里的 orderBy 参数可能应该是 allPosts 字段而不是 user 字段的参数。这样做有两个原因:(1) 从概念上讲,无论排序标准如何,您都会对 allPosts 返回的帖子进行排序 - 按照惯例,将排序放在那里才有意义; (2) allPosts 解析器可能比 user 解析器更需要该参数。

要使上述工作正常进行,您可能需要修改识别排序条件的方式(例如,将 field 设置为 user.name 等路径)。您可能还需要“提升”将用户填充到 allPosts 解析器中的逻辑。例如:

resolve(parentValue, { sortBy: { path, direction } }) {
const data = postData.map(post => {
post.user = userMap[post.user]
return post
});
// using lodash
return orderBy(data, [(post) => get(post, path)], [direction])
}

通过解析作为第四个参数传入的 info 对象,可以确定请求中其他字段(包括参数)的选择集。解析器功能。但这很痛苦,我不知道这个特殊情况是否真的证明这样做是合理的。您可以在 this answer 中阅读有关该方法的更多信息。 .

关于graphql:按嵌套字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49641885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com