首页 > 解决方案 > 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 和实际解析器之间的返回类型不匹配会在我有机会重新格式化返回值之前引发错误。

标签: postgresqlgraphqlgraphql-toolspostgraphile

解决方案


推荐阅读