Search code examples
rest.net-coregraphqlhotchocolate

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

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