1
votes

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”.

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
  }
}

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?

1

1 Answers

0
votes

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)

This is the best option performance-wise.