'Graphql hot chocolate merge data from rest endpoints

I am creating a hot chocolate service as a gateway for merging data from multiple rest endpoints. But I am having a hard time finding any resources that explain how to resolve guids to objects from other endpoints.

For example one service has a db with the products and another service has a db with the reviews.

How do I setup hot chocolate so that this query can be executed?

query {
  product(id: $id) {
    id
    title
    review {
      comment
    }
  }
}
```


Solution 1:[1]

What you had to do is create an ObjectType to resolve the collection. Something along the lines of...

using HotChocolate.Types;

public class ProductResolvers: ObjectType<Product>
{
    protected override void Configure(IObjectTypeDescriptor<Models.Product> descriptor)
    {
        descriptor.Field(fld => fld.Reviews)
                  .Resolve(async (context, ct) =>
                  {
                      var prodID = context.Parent<Models.Product>().Id);
                      var ProductReviews= await SomeMethodToGetReviews(prodID);

                      return ProductReviews;
                  });
    }
}        

Once you have the resolver, you will need to register it in your Startup

services.AddGraphQLServer()
        .AddQueryType(q => q.Name("Query"))
        .AddType<ProductsQuery>()
        .AddType<ReviewsQuery>()
        .AddType<ProductResolvers>()  // <=== Register your product resolver class here

The great thing with Hot Chocolate is that if you do not specify the Reviews in the request, then the Review service will not even be called. Very efficient...

Solution 2:[2]

I ended up using a dataloader and a extended type of the product like so:

[ExtendObjectType(typeof(Product))]
public class ProductExtensions
{
public async Task<Review> GetReviewAsync(
    [Parent] Product product,
    ReviewDataLoader dataLoader)
    {
        return await dataloader.LoadAsync(product.Id)
    }
}

Then added the extended type like so:

services
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .AddTypeExtension<ProductExtensions>()
    .AddDataLoader<ReviewDataLoader>()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kim Frost Nielsen