【问题标题】:Communication between schema stitched graphql microservices conventions模式缝合的graphql微服务约定之间的通信
【发布时间】:2019-09-30 23:34:05
【问题描述】:

我有以下我认为相当普遍的结构。我一直在寻找并且找不到任何关于模式拼接服务相互调用的推荐方式的任何信息(同时仍被前端使用)。这是我的情况:

Api 网关模式缝合:

  • 用户服务
  • 帖子服务

posts 服务使用 mongodb,users 服务使用 PostgreSQL。帖子服务的架构仅包含 user_id 而不是完整用户。当我需要一页帖子(带有相应的用户信息)时,我正在使用帖子服务中的 getPosts 解析器中的 node-fetch 调用用户服务,如下所示:

{
  getUsers(user_id__in:[1,5,9,3]){
    username
    join_date
  }
}

与 apollo-graphql 的其余部分的优雅相比,这个解决方案感觉有点“肮脏”。

是否更常见的是忽略 graphql 部分来解析数据并使用 apollo-graphql 的底层 express 服务器提供的典型 rest 端点结构?如果不是,我应该直接调用其他服务还是通过 api 网关调用它们?如果我应该通过 api 网关调用它们,有没有一种内置的优雅方式可以使用某些 Apollo 功能调用 api 网关(因为服务是模式拼接的)。

【问题讨论】:

    标签: node.js graphql apollo


    【解决方案1】:

    您的问题没有显示任何现有的 API 网关代码,但我假设您正在拼接您的架构 as described in the docs。每个服务的模式应该只提供适合其特定领域的字段。例如,帖子服务模式不应包含对用户的任何引用。当您将架构拼接在一起时,您可以通过提供链接不同服务的附加字段扩展现有类型。

    const extensions = `
    extend type User {
      posts
    }
    
    extend type Post {
      user
    }
    `
    
    const mergedSchema = mergeSchemas({
      schemas: [
        usersSchema,
        postsSchema,
        extensions,
      ],
      resolvers: {
        User: {
          posts: {
            fragment: `... on User { id }`,
            resolve(user, args, context, info) {
              return info.mergeInfo.delegateToSchema({
                schema: postsSchema,
                operation: 'query',
                fieldName: 'posts',
                args: {
                  userId: user.id,
                },
                context,
                info,
              });
            },
          },
        },
        Post: {
          user: {
            fragment: `... on Post { userId }`,
            resolve(post, args, context, info) {
              return info.mergeInfo.delegateToSchema({
                schema: postsSchema,
                operation: 'query',
                fieldName: 'user',
                args: {
                  id: post.userId,
                },
                context,
                info,
              });
            },
          },
        },
      },
    });
    

    在这里,我们扩展了用户服务中的 User 类型以包含 posts 字段。我们使用delegateToSchema 表示这个额外的字段实际上应该由posts 服务的模式通过查询posts 并将用户ID 作为userId 参数传递(实际的字段和参数名称需要与您的模式匹配)。我们类似地为每个 Post 添加一个 user 字段,并将解析该字段委托给用户服务架构。

    请查看docs了解更多详情。

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 2020-10-05
      • 2016-06-10
      • 2016-03-05
      • 2018-01-22
      • 1970-01-01
      • 2021-01-17
      • 2016-08-10
      • 2019-01-18
      相关资源
      最近更新 更多