postgresql - GraphQL - 将 JSON 解析为 graphql 类型数组以支持批量查询
问题描述
我有一组使用graphql-tools
模式拼接在网关中组合在一起的 graphql 服务。
以下是一些示例代码供参考:
async function makeGatewaySchema() {
// define the remote executors, introspect the subschemas, etc.
return stitchSchemas({
subschemas: [
{
schema: postSubschema,
executor: postExecutor,
batch: true,
},
{
schema: userSubschema,
executor: userExecutor,
batch: true,
},
],
typeDefs: `
...
extend type User {
posts: [Post]
batchPostsJSON: JSON
batchPosts: [Post]
}
...
`,
resolvers: {
User: {
posts: {
selectionSet: "{ id }",
resolve(user, args, context, info) {
return delegateToSchema({
schema: schemaPost,
operation: "query",
fieldName: "postsByUserId",
args: { id: user.id },
context,
info,
});
},
},
batchPostsJSON: {
selectionSet: "{ id }",
resolve(user, args, context, info) {
return batchDelegateToSchema({
schema: schemaFavorite,
operation: "query",
fieldName: "postsByUserIds",
key: user.id,
argsFromKeys: (ids) => ({ ids }),
valuesFromResults: (results, keys) => {
return keys.map((id) => {
return results.filter((f) => f.user_id === id);
});
},
context,
info,
});
},
},
batchPosts: {
selectionSet: "{ id }",
resolve(user, args, context, info) {
return batchDelegateToSchema({
schema: schemaPost,
operation: "query",
fieldName: "postsByUserIds",
key: user.id,
argsFromKeys: (ids) => ({ ids }),
valuesFromResults: (results, keys) => {
// doesn't matter, we don't get here
},
context,
info,
});
},
},
},
},
});
}
在上面的示例代码中,我有三种方法来获取与用户关联的帖子:
1:User.posts
这工作正常,但不是批处理
2:User.batchPostsJSON
这非常好地批处理并且完美地解决了一个问题:JSON
返回类型不允许我查询Post
字段 - 无论如何我都会得到所有字段。更糟糕的是,如果Post
与某些第三种类型有关,我将无法遵循这种关系。
3:User.batchPosts
这允许我查询 的字段Post
,但会引发异常 - 我已将返回类型定义为 的数组Post
,但返回的结果JSON
是我在网关中收到错误。
有没有办法处理子模式返回的 JSON 并假装我真的[Post]
回来了?当我valueFromResults
完成时,这就是它的样子。问题是我的 typedef 和实际解析器之间的返回类型不匹配会在我有机会重新格式化返回值之前引发错误。
解决方案
推荐阅读
- linkedin - LinkedIn Talent Solutions Partnership
- c++ - 我可以知道为什么这个函数的参数不是 int 类型吗?我不明白这里指针的整个概念
- elixir - 测试一个长生不老药功能
- arrays - 我不明白为什么我的程序中的 while 循环不起作用
- python - 完整的 HTML 没有被 BeautifulSoup 解析 - 这是因为动态 HTML 吗?
- android - Add Google Assistant routines from my app
- mysql - Mysql2::Error::ConnectionError: Can't connect to MySQL server on 'mysql' (111 "Connection refused")
- streaming - Apache Beam:使用 Withtimestamp 分配事件时间时出错
- android - Firebase 远程配置:FirebaseInstanceId 为空
- reactjs - Webpack 返回 ValidationError: CSS Loader Invalid Options