合并外部和本地数据并使用 graphql 将其作为单个数据进行查询

Merge external and local data and query it as single data using graphql

假设我有来自名为“posts”的外部 API 的数据。 “posts”中的每个 post 都有“标题”和“内容”字段。这个外挂我没法控制API,“posts”就这么来了

在我的本地应用程序中,我想向每个 post 添加更多字段。这些字段是“类别”和“标签”。

然后,我想使用 graphql 查询我的后端 API,因此我的查询从外部 API 和本地数据中提取数据。例如

{
  post (id: 2){
    title, # external
    content, # external
    category, # local
    tags # local
  }
}

我怎样才能完成它? 我是否应该创建第三个数据(模型)以某种方式将外部数据和本地数据合并在一起,然后查询该数据?或者,我的本地字段是否应该以某种方式从外部节点提取 ID 并将它们与它们自己的数据一起保存在这些字段突变中?

非常简单,您可以创建一个函数,在调用本地数据的同时调用外部 API,returns 合并对象:

function fetchPost(postId) {

  return Promise.all([
    getPostFromExternalAPI(postId),
    getCategoryForPost(postId),
    getTagsForPost(postId),
  ])
  .then(([ post, category, tags ]) => {
    return Object.assign(post, {
      category,
      tags,
    });
  });
}

然后,您的 post 字段解析器将具有以下形状:

const postFieldResolver = (_, args, context) => fetchPost(args.id)

这是性能方面的最佳选择。