To view how schema stitching works, I create two new projects:
graphqlWarehouse
: it's a minimal grapghQL server for Warehouse Bounded ContextgraphqlGateway
: it's a minimal grapghQL server that works as graphQL gateway between the two others graphQL server (books and warehouse)
# create the gateway project
dotnet new web -n graphqlGateway
# add dependencies to the gateway project
dotnet add ./graphqlGateway package HotChocolate.AspNetCore --version 12.1.0
dotnet add ./graphqlGateway package HotChocolate.Stitching --version 12.1.0
# add web project to the solution
dotnet sln add graphqlGateway
####
# create the Bounded Context project
dotnet new web -n graphqlWarehouse
# add dependencies to the gateway project
dotnet add ./graphqlWarehouse package HotChocolate.AspNetCore --version 12.1.0
dotnet add ./graphqlWarehouse package HotChocolate.Data.MongoDb --version 12.1.0
dotnet add ./graphqlWarehouse package MongoDB.Driver --version 2.12.1
# add web project to the solution
dotnet sln add graphqlWarehouse
With schema stitching each of the projects involved don't know anything about other bounded contexts or the gateway. Only the gateway knows how to connect the graphQL servers and how to stich the types togher.
Here I create the composite schema:
builder.Services.AddHttpClient("books", c => c.BaseAddress = new Uri("https://localhost:7059/graphql"));
builder.Services.AddHttpClient("inventories", c => c.BaseAddress = new Uri("https://localhost:7016/graphql"));
builder.Services
.AddLogging()
.AddGraphQLServer()
.AddRemoteSchema("books")
.AddRemoteSchema("inventories")
.AddTypeExtensionsFromFile("./Stitching.graphql");
;
in the Stitching.graphql
file we can create connection between the different schemas:
extend type Query {
topBooks(first: Int = 5): BooksConnection @delegate(schema: "books", path: "books")
}
extend type Book {
availability: [Inventory!]! @delegate(schema: "inventories", path: "inventoriesByProductId(productId: $fields:id)")
}
In particulare, with availability
field we allow the graphQL client to compose query provided by different servers using the gateway, eg:
{
books(first: 2) {
nodes {
id
title
availability {
inStock
availableQty
}
}
}
}