graphql - 带有数组参数的嵌套 GraphQL 查询
问题描述
我正在使用apollo-datasource-rest
并apollo-server-lambda
试图弄清楚如何将查询映射到特定的解析器。我有以下模式,其中plan
查询应该返回用户列表(应该由users
查询而不是user
查询驱动)。
type Query {
user(user_id: String, username: String): User
users(user_ids: [String!]): [User!]
plan(plan_id: String): Plan
}
type User {
id: String
username: String
first: String
last: String
image: String
}
type Plan {
title: String
image: String
attending: [User]
}
plan
查询解析器数据源如下:
planReducer(data) {
return {
image: data.public.info.image,
title: data.public.info.title,
attending: Object.keys(data.public.attending)
}
}
data.public.attending
在planReducer
返回一个 s 数组,user_id
然后我希望能够将其输入到我的users
查询中,而不是我的user
查询。
这些是我目前的解析器:
user: (_, { username }, { dataSources }) =>
dataSources.userData.getUserByUsername({ username: username }),
users: async (_, { user_ids }, { dataSources }) => {
const usersArray = await dataSources.userData.getUsersByIds({ userIds: user_ids })
return usersArray
},
plan: async (_, { plan_id }, { dataSources }) => {
return dataSources.planData.getPlanById({ planId: plan_id })
}
解决方案
您的解析器映射应如下所示:
const resolvers = {
Query: {
plan: async (_parent, { plan_id: planId }, { dataSources }) => (
dataSources.planData.getPlanById({ planId })
)
},
Plan: {
users: async ({ user_ids: userIds }, _variables, { dataSources }) => (
dataSources.userData.getUsersByIds({ userIds })
)
}
}
其中的每个键都Query
应该是一个解析器,对应于Query
架构根中定义的查询。作为根的直接子级的键,在这种情况下,当从内的解析器Plan
返回时,将用于解析它们对应的类型。plan
Query
如果未定义解析器,GraphQL 将回退到默认解析器,在这种情况下,该解析器如下所示:
const resolvers = {
Plan: {
title: (parent) => parent.title,
image: (parent) => parent.image,
}
}
通过指定自定义解析器,您可以根据父解析器的返回值计算要返回给客户端的字段。
推荐阅读
- javascript - 将第一次出现滚动到 div 内的顶部位置
- sql - 获取最后插入的 id 作为多插入的一部分?
- powershell - Password Generator - Generate password on demand
- jquery - 不刷新使用Ajax和node js从SQL数据库获取数据
- visual-studio - 如何从同一个解决方案运行多个 Web API?
- php - 在 Laravel 5.6 中添加 GELF 记录器后出现“您的配置文件不可序列化”错误消息
- python-3.x - 如何通过 Selenium 在 Chrome 浏览器中使用 Tor
- javascript - 使用 URL 哈希删除特定 div 上的活动类
- git - 使用 Git 提交后的缩进问题
- javascript - 将 Firestore 文件分配给变量,并在 HTML-Angualr 7 中显示