合并外部和本地数据,并使用graphql将其查询为单个数据 [英] Merge external and local data and query it as single data using graphql

查看:40
本文介绍了合并外部和本地数据,并使用graphql将其查询为单个数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有来自外部API(称为帖子")的数据.帖子"中的每个帖子都有标题"和内容"字段.我无法控制此外部API,帖子"原样出现.

Let's say I have data that comes from external API called "posts". Each post in the "posts" has "title" and "content" field. I have no way to control this external API, "posts" comes as it is.

在我的应用程序中,我想在本地为每个帖子添加更多字段.这些字段是类别"和标签".

In my application, locally, I want to add couple more fields to each post. These fields are "category" and "tags".

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

Then, I want to query my backend API using graphql, so my query pulls data from both external API and local one. For instance

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

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

How can I accomplish it? Should I make a third piece of data (model) that somehow will merge together both external and local data together and then query this data? Or, should my local fields somehow extract IDs from external nodes and save them along with their own data on these fields mutation?

推荐答案

实际上,您可以创建一个函数,该函数在对本地数据的调用的同时进行对外部API的调用,并返回合并的对象:

Really simply, you can create a function that make the calls to the external API at the same time of the calls to your local data, and returns a merged object:

function fetchPost(postId) {

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

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

Then, your post field resolver will have the shape:

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

这是性能最佳的选择.

这篇关于合并外部和本地数据,并使用graphql将其查询为单个数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆