### Setup and Test Apollo Federation Compatibility Source: https://github.com/apollographql/federation-hotchocolate/blob/main/Compatibility/CodeFirst/README.md These commands install the required testing dependencies, export the GraphQL schema from a .NET HotChocolate project, and run the compatibility test suite via Docker Compose. ```shell npm install --dev @apollo/federation-subgraph-compatibility dotnet run --project Compatibility/CodeFirst/CodeFirst.csproj schema export --output products.graphql npx fedtest docker --compose Compatibility/CodeFirst/docker-compose.yaml --schema Compatibility/CodeFirst/products.graphql ``` -------------------------------- ### Start Apollo Federated Router Source: https://github.com/apollographql/federation-hotchocolate/blob/main/examples/README.md Command to initialize the Apollo Router using a supergraph configuration file. This orchestrates the federated subgraphs into a single unified API. ```shell rover dev --supergraph-config examples/supergraph.yaml ``` -------------------------------- ### Implement Federated Subgraph Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt A complete example of a federated product subgraph, including entity definition with [Key], reference resolution, and repository registration. ```csharp [Key("upc")] public class Product { public string Upc { get; } public string Name { get; } public int Price { get; } public int Weight { get; } [ReferenceResolver] public static Product GetByIdAsync(string upc, ProductRepository productRepository) => productRepository.GetById(upc); } // Program.cs registration builder.Services.AddSingleton(); builder.Services .AddGraphQLServer() .AddApolloFederationV2() .AddQueryType() .RegisterService(); ``` -------------------------------- ### Install Apollo Federation via NuGet Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Add the necessary package references to your .csproj file to enable Apollo Federation support in your HotChocolate project. ```xml ``` -------------------------------- ### Install Federation Subgraph Compatibility Script (npm) Source: https://github.com/apollographql/federation-hotchocolate/blob/main/Compatibility/AnnotationBased/README.md Installs the @apollo/federation-subgraph-compatibility package as a development dependency. This script is essential for running compatibility tests against your Apollo Federation subgraph. ```shell npm install --dev @apollo/federation-subgraph-compatibility ``` -------------------------------- ### Start HotChocolate Subgraph Services Source: https://github.com/apollographql/federation-hotchocolate/blob/main/examples/README.md Commands to launch individual federated subgraph services using the .NET CLI. These services represent different domains like Accounts, Inventory, Products, and Reviews. ```shell dotnet run --project examples/AnnotationBased/Accounts/Accounts.csproj dotnet run --project examples/AnnotationBased/Inventory/Inventory.csproj dotnet run --project examples/AnnotationBased/Products/Products.csproj dotnet run --project examples/AnnotationBased/Reviews/Reviews.csproj ``` -------------------------------- ### Configure Apollo Federation v2 Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Registers Federation v2 support within the Hot Chocolate GraphQL server setup. ```csharp using ApolloGraphQL.HotChocolate.Federation; var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2() .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Execute Federated GraphQL Query Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Example of a GraphQL query that spans multiple federated subgraphs, requesting fields from both the 'me' and 'topProducts' services. ```graphql query ExampleQuery { me { id username } topProducts { upc name price inStock reviews { id body author { id username } } } } ``` -------------------------------- ### Register Apollo Federation in GraphQL Server Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Configure your HotChocolate GraphQL server to support Apollo Federation by adding the federation services during the builder setup. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Configure Subgraph Contact Information Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Shows how to add team contact details to a subgraph schema using the [Contact] attribute or the schema configuration action in the HotChocolate server setup. ```csharp [Contact("MyTeamName", "https://myteam.slack.com/archives/teams-chat-room-url", "send urgent issues to [#oncall](https://yourteam.slack.com/archives/oncall)")] public class CustomSchema : FederatedSchema { } var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddType() .AddApolloFederationV2(new CustomSchema()); ``` ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(schemaConfiguration: s => { s.Contact("MyTeamName", "https://myteam.slack.com/archives/teams-chat-room-url", "send urgent issues to [#oncall](https://yourteam.slack.com/archives/oncall)"); }); ``` -------------------------------- ### Project Build and Test Commands Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Standard shell commands for restoring dependencies, building the project, and running tests within the repository. ```shell # install dependencies dotnet restore # build project dotnet build # run tests dotnet test ``` -------------------------------- ### Build project with .NET CLI Source: https://github.com/apollographql/federation-hotchocolate/blob/main/CONTRIBUTING.md Commands to restore dependencies and build the project from the root directory. This is used to verify changes locally. ```shell dotnet restore dotnet build ``` -------------------------------- ### Code-First Key Configuration Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Configure federation directives using the code-first approach with type descriptors for more granular control. ```APIDOC ## Code-First Key Configuration Configure federation directives using the code-first approach with type descriptors for more granular control. ### Example Usage: ```csharp public class Product { public Product(string id, string name, string description) { Id = id; Name = name; Description = description; } [ID] public string Id { get; } public string Name { get; } public string? Description { get; } } public class ProductType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor .Key("id") .ResolveReferenceWith(t => GetProduct(default!, default!)); } private static Product GetProduct( string id, ProductRepository productRepository) => productRepository.GetById(id); } // Program.cs setup: var builder = WebApplication.CreateBuilder(args); builder.Services .AddSingleton(); builder.Services .AddGraphQLServer() .AddApolloFederationV2() .AddQueryType() .AddType() .RegisterService(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` ``` -------------------------------- ### Run Federation Compatibility Tests (npx) Source: https://github.com/apollographql/federation-hotchocolate/blob/main/Compatibility/AnnotationBased/README.md Executes the Apollo Federation compatibility tests using the 'fedtest' command-line tool. It requires a Docker Compose file for setting up the test environment and the generated GraphQL schema file. ```shell npx fedtest docker --compose Compatibility/AnnotationBased/docker-compose.yaml --schema Compatibility/AnnotationBased/products.graphql ``` -------------------------------- ### Configure Federation v2 with Schema Configuration Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Applies custom schema directives and metadata using a configuration action. ```csharp using ApolloGraphQL.HotChocolate.Federation; var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(schemaConfiguration: s => { s.Contact("MyTeamName", "https://myteam.slack.com/archives/teams-chat-room-url", "send urgent issues to [#oncall](https://yourteam.slack.com/archives/oncall)"); s.Link("https://myspecs.dev/myCustomDirective/v1.0", new string[] { "@custom" }); s.ComposeDirective("@custom"); }) .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Configure Federation v2 with Specific Version Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Enables Federation v2 with a specific version target (e.g., 2.3). ```csharp using ApolloGraphQL.HotChocolate.Federation; using ApolloGraphQL.HotChocolate.Federation.Two; var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(FederationVersion.FEDERATION_23) .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Generate Test Schema (dotnet CLI) Source: https://github.com/apollographql/federation-hotchocolate/blob/main/Compatibility/AnnotationBased/README.md Uses the .NET CLI to run a specific project and export the generated GraphQL schema to a file named 'products.graphql'. This schema is used as input for the compatibility tests. ```shell dotnet run --project Compatibility/AnnotationBased/AnnotationBased.csproj schema export --output products.graphql ``` -------------------------------- ### Implement Entity Interfaces Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Shows how to define an entity interface with @key and extend it in other subgraphs using @interfaceObject to add fields across all implementations. ```csharp [InterfaceType] [KeyInterface("id")] public interface Product { [ID] string Id { get; } string Name { get; } } [Key("id")] public class Book : Product { [ID] public string Id { get; set; } public string Name { get; set; } public string Content { get; set; } } [Key("id")] [InterfaceObject] public class Product { [ID] public string Id { get; set; } public List Reviews { get; set; } } ``` -------------------------------- ### Run unit tests Source: https://github.com/apollographql/federation-hotchocolate/blob/main/CONTRIBUTING.md Command to execute the unit test suite using the .NET CLI. This ensures code coverage and validates schema federation logic. ```shell dotnet test ``` -------------------------------- ### Export GraphQL Schema at Build Time Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Shows how to enable GraphQL commands in a .NET application to export the schema file using the Hot Chocolate CLI. ```csharp using ApolloGraphQL.HotChocolate.Federation; var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2() .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.RunWithGraphQLCommands(args); ``` ```bash dotnet run -- schema export --output schema.graphql ``` -------------------------------- ### Generate GraphQL Schema at Build Time with HotChocolate Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md This snippet shows how to configure a HotChocolate server to allow schema generation at build time using the command-line interface. It requires adding the HotChocolate.AspNetCore.CommandLine package and calling RunWithGraphQLCommands. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2() // register your types and services ; var app = builder.Build(); app.MapGraphQL(); app.RunWithGraphQLCommands(args); ``` -------------------------------- ### Configure Federation Keys with Code-First Descriptors Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Provides a pattern for configuring federation keys and reference resolvers using the Hot Chocolate ObjectTypeDescriptor API. ```csharp using HotChocolate.Types; public class ProductType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Key("id").ResolveReferenceWith(t => GetProduct(default!, default!)); } } ``` -------------------------------- ### Code-First Entity Configuration Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md How to configure federated entities using the HotChocolate code-first approach. ```APIDOC ## Code-First Entity Configuration ### Description Use the `ObjectType` descriptor to manually configure federation keys and reference resolvers for your entities. ### Implementation ```csharp public class ProductType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor .Key("id") .ResolveReferenceWith(t => GetProduct(default!, default!)); } } ``` ### Resulting Schema ```graphql type Product @key(fields: "id") { id: ID! name: String! description: String } ``` ``` -------------------------------- ### Federation Directive Configuration Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Overview of available Federation v1 and v2 directives and how to apply them to GraphQL types and fields. ```APIDOC ## Federation Directives ### Description HotChocolate supports Apollo Federation directives to enable distributed GraphQL architectures. These directives allow for entity definition, field sharing, and schema composition. ### Federation v1 Directives - **@extends**: Used to extend types defined in other subgraphs. - **@external**: Marks a field as defined in another subgraph. - **@key**: Defines the primary key for an entity. - **@provides**: Specifies fields provided by this subgraph. - **@requires**: Specifies fields required from other subgraphs. ### Federation v2 Directives - **@tag**: Adds metadata to schema elements. - **@authenticated**: Marks elements as requiring authentication. - **@composeDirective**: Allows composition of custom directives. - **@inaccessible**: Hides elements from the gateway. - **@interfaceObject**: Enables interface-based entities. - **@link**: Imports external definitions. - **@requiresScopes**: Defines authorization scopes. - **@shareable**: Allows fields to be shared across subgraphs. ``` -------------------------------- ### Configure Federation v2 with Custom FederatedSchema Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Uses a custom class inheriting from FederatedSchema for advanced schema customization. ```csharp [Contact("MyTeamName", "https://myteam.slack.com/archives/teams-chat-room-url", "send urgent issues to [#oncall](https://yourteam.slack.com/archives/oncall)")] [ComposeDirective("@custom")] [Link("https://myspecs.dev/myCustomDirective/v1.0", new string[] { "@custom" })] public class CustomSchema : FederatedSchema { public CustomSchema() : base(FederationVersion.FEDERATION_25) { } } var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(new CustomSchema()) .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Manual Entity Resolver Implementation Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Demonstrates how to manually resolve an entity when auto-mapping is not supported for complex types. It uses the [ReferenceResolver] attribute and accepts an ObjectValueNode from the local state. ```csharp [ReferenceResolver] public static Foo GetByFooBar( [LocalState] ObjectValueNode data Data repository) { // TODO implement logic here by manually reading values from local state data } ``` -------------------------------- ### Configure Federated Schema via Action Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Shows an alternative approach to configuring the federated subgraph by providing an action delegate directly to the AddApolloFederationV2 method. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(schemaConfiguration: s => { // apply your directive here }); ``` -------------------------------- ### Execute Federated GraphQL Query Source: https://github.com/apollographql/federation-hotchocolate/blob/main/examples/README.md A sample GraphQL query demonstrating data fetching across multiple federated services, including User and Product types with nested Review data. ```graphql query ExampleQuery { me { id } topProducts { inStock name price reviews { author { id name } body id } } } ``` -------------------------------- ### Code-First External and Requires Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Configure `@external` and `@requires` directives using descriptor extensions. ```APIDOC ## Code-First External and Requires Configure `@external` and `@requires` directives using descriptor extensions. ### Example Usage: ```csharp public class Product { public string Id { get; set; } public int Weight { get; set; } public int Price { get; set; } } public class ProductType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor .Key("id") .ResolveReferenceWith(t => ResolveProduct(default!)); descriptor .Field(p => p.Weight) .External(); descriptor .Field(p => p.Price) .External(); descriptor .Field("shippingEstimate") .Type() .Requires("weight price") .Resolve(ctx => { var product = ctx.Parent(); return product.Weight > 0 ? (product.Price / product.Weight) * 10 : 0; }); } private static Product ResolveProduct(string id) => new() { Id = id }; } ``` ``` -------------------------------- ### Define Federated Product Type with Code First in C# Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Demonstrates how to define a federated entity type 'Product' using the code-first approach in C# with Hot Chocolate. It includes setting the @key directive and configuring the reference resolver. ```csharp public class Product { public Product(string id, string name, string? description) { Id = id; Name = name; Description = description; } [ID] public string Id { get; } public string Name { get; } public string? Description { get; } } public class ProductType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor .Key("id") .ResolveReferenceWith(t => GetProduct(default!, default!)); } private static Product GetProduct( string id, ProductRepository productRepository) => productRepository.GetById(upc); ``` ```graphql type Product @key(fields: "id") { id: ID! name: String! description: String } ``` -------------------------------- ### Apply Composed Directives Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Demonstrates how to use @composeDirective and @link to include custom directives in the Supergraph schema, either via class attributes or configuration actions. ```csharp [ComposeDirective("@custom")] [Link("https://myspecs.dev/myCustomDirective/v1.0", new string[] { "@custom" })] public class CustomSchema : FederatedSchema { } builder.Services .AddGraphQLServer() .AddApolloFederationV2(new CustomSchema()); // Alternative via configuration action builder.Services .AddGraphQLServer() .AddApolloFederationV2(schemaConfiguration: s => { s.Link("https://myspecs.dev/myCustomDirective/v1.0", new string[] { "@custom" }); s.ComposeDirective("@custom"); }); ``` -------------------------------- ### Configure Apollo Federation v1 Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Registers Federation v1 support for legacy GraphQL schemas. ```csharp using ApolloGraphQL.HotChocolate.Federation; var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederation() .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Migrate to ApolloGraphQL Federation Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Provides the necessary changes to NuGet package references and namespace imports when migrating from the legacy HotChocolate.Federation package. ```xml - + ``` ```csharp - using HotChocolate.ApolloFederation; + using ApolloGraphQL.HotChocolate.Federation; ``` -------------------------------- ### Define External Fields and Requirements Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Illustrates how to use .External() and .Requires() within a descriptor to handle federated field dependencies and external data requirements. ```csharp descriptor.Field(p => p.Weight).External(); descriptor.Field("shippingEstimate") .Type() .Requires("weight price") .Resolve(ctx => { /* logic */ }); ``` -------------------------------- ### Customize Federated Schema with Attributes Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Demonstrates how to create a custom FederatedSchema class by extending SchemaTypeDescriptorAttribute to apply custom directives to the GraphQL schema. ```csharp [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true, AllowMultiple = true)] public sealed class CustomAttribute : SchemaTypeDescriptorAttribute { public override void OnConfigure(IDescriptorContext context, ISchemaTypeDescriptor descriptor, Type type) { // configure your directive here } } [Custom] public class CustomSchema : FederatedSchema { public CustomSchema() : base(FederationVersion.FEDERATION_23) { } } builder.Services .AddGraphQLServer() .AddApolloFederationV2(new CustomSchema()); ``` -------------------------------- ### Configure @provides and @shareable Directives in C# Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt This C# code configures the @provides and @shareable directives using descriptor extensions in Hot Chocolate. It demonstrates how to specify fields that a subgraph provides and mark fields as shareable across subgraphs. Dependencies include HotChocolate.Types. ```csharp using HotChocolate.Types; public class ReviewType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor .Key("id") .ResolveReferenceWith(t => ResolveReview(default!, default!)); descriptor .Field(r => r.Author) .Provides("username") .Resolve(ctx => { var review = ctx.Parent(); var repository = ctx.Service(); return repository.GetUserById(review.AuthorId); }); descriptor .Field(r => r.Body) .Shareable(); } private static Review ResolveReview(string id, ReviewRepository repository) => repository.GetById(id); } ``` -------------------------------- ### Define Provides Attribute for Router Optimization Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [Provides] attribute acts as a hint to the router, specifying fields that can be resolved locally. This helps optimize query paths by reducing the need for cross-subgraph requests. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("id")] public class Review { public Review(string id, string body, string authorId, string upc) { Id = id; Body = body; AuthorId = authorId; Product = new Product(upc); } public string Id { get; } public string Body { get; } public string AuthorId { get; } public Product Product { get; } [Provides("username")] public Task GetAuthorAsync(UserRepository repository) => repository.GetUserById(AuthorId); } ``` -------------------------------- ### Configure Custom Query Types Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Explains how to register a custom root Query type in the HotChocolate server configuration when the default 'Query' name is not desired. ```csharp public class CustomQuery { public Foo? GetFoo([ID] string id, Data repository) => repository.Foos.FirstOrDefault(t => t.Id.Equals(id)); } var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .ModifyOptions(opts => opts.QueryTypeName = "CustomQuery") .AddApolloFederationV2() .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Specify Federation Version in HotChocolate Configuration Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Demonstrates how to explicitly set the Federation version when configuring HotChocolate's Apollo Federation support. This can be done by passing a FederationVersion enum value or a custom FederatedSchema class. ```csharp builder.Services .AddGraphQLServer() .AddApolloFederationV2(FederationVersion.FEDERATION_23) // register your types and services ; ``` ```csharp public class CustomSchema : FederatedSchema { public CustomSchema() : base(FederationVersion.FEDERATION_23) { } } builder.Services .AddGraphQLServer() .AddApolloFederationV2(new CustomSchema()) // register your types and services ; ``` -------------------------------- ### Create a new Git branch Source: https://github.com/apollographql/federation-hotchocolate/blob/main/CONTRIBUTING.md Command to create and switch to a new feature branch in Git. This ensures that work for each feature or issue is isolated. ```shell git checkout -b my-new-feature ``` -------------------------------- ### Configure Custom Root Query Type Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Demonstrates how to override the default 'Query' type name in Hot Chocolate by modifying the server options during service registration. ```csharp using ApolloGraphQL.HotChocolate.Federation; public class CustomQuery { public Foo? GetFoo([ID] string id, Data repository) => repository.Foos.FirstOrDefault(t => t.Id.Equals(id)); } var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .ModifyOptions(opts => opts.QueryTypeName = "CustomQuery") .AddApolloFederationV2() .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### Implement Entity Resolver with [ReferenceResolver] Attribute (C#) Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [ReferenceResolver] attribute designates a public static method as the entity resolver. This method is invoked by the gateway's query planner to resolve an entity based on its unique identifier. It requires the ApolloGraphQL.HotChocolate.Federation namespace. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("upc")] public class Product { public Product(string upc, string name, int price, int weight) { Upc = upc; Name = name; Price = price; Weight = weight; } public string Upc { get; } public string Name { get; } public int Price { get; } public int Weight { get; } [ReferenceResolver] public static Product GetByIdAsync( string upc, ProductRepository productRepository) => productRepository.GetById(upc); } public class ProductRepository { private readonly Dictionary _products; public ProductRepository() { _products = CreateProducts().ToDictionary(p => p.Upc); } public Product GetById(string upc) => _products[upc]; private static IEnumerable CreateProducts() { yield return new Product("1", "Table", 899, 100); yield return new Product("2", "Couch", 1299, 1000); yield return new Product("3", "Chair", 54, 50); } } ``` -------------------------------- ### Define Non-Resolvable Entity Stubs Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Explains how to define a stub object using the [NonResolvableKeyAttribute] to represent an entity in a subgraph without contributing fields to it. ```csharp public class Review { public Review(Product product, int score) { Product = product; Score = score; } public Product Product { get; } public int Score { get; } } [NonResolvableKey("id")] public class Product { public Product(string id) { Id = id; } public string Id { get; } } ``` -------------------------------- ### Extend Interfaces with InterfaceObject Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Demonstrates using the [InterfaceObject] attribute to extend interfaces across subgraphs in Federation v2.3+. This allows adding fields to interface implementations without modifying the original subgraph definition. ```csharp using ApolloGraphQL.HotChocolate.Federation; [InterfaceType] [KeyInterface("id")] public interface Product { [ID] string Id { get; } string Name { get; } } [Key("id")] [InterfaceObject] public class Product { [ID] public string Id { get; set; } public List Reviews { get; set; } } ``` -------------------------------- ### Generated Federated GraphQL Schema Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md The resulting GraphQL schema representation of the federated Product entity with the @key directive. ```graphql type Product @key(fields: "id") { id: ID! name: String! description: String } ``` -------------------------------- ### Implement Access Control with @requiresScopes Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Demonstrates how to restrict access to GraphQL fields using the [RequiresScopes] attribute in C#. This maps to the @requiresScopes directive in the generated GraphQL schema. ```csharp public class Query { [RequiresScopes(scopes: new string[] { "scope1, scope2", "scope3" })] [RequiresScopes(scopes: new string[] { "scope4" })] public Product? GetProduct([ID] string id, Data repository) => repository.Products.FirstOrDefault(t => t.Id.Equals(id)); } ``` ```graphql type Query { product(id: ID!): Product @requiresScopes(scopes: [ [ "scope1, scope2", "scope3" ], [ "scope4" ] ]) } ``` -------------------------------- ### Map Complex Arguments with [Map] Attribute in C# Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt This C# code demonstrates the use of the [Map] attribute to map complex argument representations to simpler values in entity resolvers for Apollo Federation with Hot Chocolate. It shows how to directly map nested fields and how to handle manual parsing for complex cases using [LocalState]. Dependencies include ApolloGraphQL.HotChocolate.Federation. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("nested { id }")] public class ComplexEntity { public ComplexEntity(string nestedId) { NestedId = nestedId; } public string NestedId { get; } [ReferenceResolver] public static ComplexEntity GetByNestedId( [Map("nested.id")] string nestedId, EntityRepository repository) => repository.GetByNestedId(nestedId); } // For complex cases requiring manual parsing: [ReferenceResolver] public static Foo GetByFooBar( [LocalState] ObjectValueNode data, Data repository) { // Manually parse the representation object var value = data.Fields.FirstOrDefault(f => f.Name.Value == "bar")?.Value; return repository.GetFoo(value?.ToString()); } ``` -------------------------------- ### Define Federated Entities with Attributes Source: https://github.com/apollographql/federation-hotchocolate/blob/main/README.md Use the [Key] and [ReferenceResolver] attributes to define federated entities that can be identified and resolved across a supergraph. ```csharp [Key("id")] public class Product { public Product(string id, string name, string? description) { Id = id; Name = name; Description = description; } [ID] public string Id { get; } public string Name { get; } public string? Description { get; } [ReferenceResolver] public static Product GetByIdAsync( string id, ProductRepository productRepository) => productRepository.GetById(id); } ``` -------------------------------- ### Compose Custom Directives with ComposeDirective in C# Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt This C# code demonstrates how to use the ComposeDirective attribute to ensure custom directives are preserved in the Supergraph schema. It also uses the Link attribute to specify the URL and imported directives. Dependencies include ApolloGraphQL.HotChocolate.Federation and ApolloGraphQL.HotChocolate.Federation.Two. ```csharp using ApolloGraphQL.HotChocolate.Federation; using ApolloGraphQL.HotChocolate.Federation.Two; [ComposeDirective("@custom")] [Link("https://myspecs.dev/myCustomDirective/v1.0", new string[] { "@custom" })] public class CustomSchema : FederatedSchema { public CustomSchema() : base(FederationVersion.FEDERATION_25) { } } var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(new CustomSchema()) .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); // Generated GraphQL schema: // extend schema // @link(url: "https://specs.apollo.dev/federation/v2.5", import: [...]) // @link(url: "https://myspecs.dev/myCustomDirective/v1.0", import: ["@custom"]) // @composeDirective(name: "@custom") ``` -------------------------------- ### Define Federated Entity with Composite [Key] Attribute (C#) Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [Key] attribute can be used with multiple fields to define a composite key for a federated entity. This is useful when a single field is not sufficient to uniquely identify an entity. It requires the ApolloGraphQL.HotChocolate.Federation namespace. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("id name")] public class Product { public Product(string id, string name, string sku) { Id = id; Name = name; Sku = sku; } [ID] public string Id { get; } public string Name { get; } public string Sku { get; } [ReferenceResolver] public static Product GetByIdAndNameAsync( string id, string name, ProductRepository productRepository) => productRepository.GetByIdAndName(id, name); } ``` -------------------------------- ### Restrict Access with RequiresScopes Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Shows how to apply the [RequiresScopes] attribute to secure GraphQL fields based on JWT scopes. This feature requires Federation v2.5+. ```csharp using ApolloGraphQL.HotChocolate.Federation; public class Query { [RequiresScopes(scopes: new string[] { "scope1, scope2", "scope3" })] public Product? GetProduct([ID] string id, Data repository) => repository.Products.FirstOrDefault(t => t.Id.Equals(id)); } ``` -------------------------------- ### Require Authentication with ApolloAuthenticated Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Implements the [ApolloAuthenticated] attribute to mark specific fields or types as requiring an authenticated user context. Available in Federation v2.5+. ```csharp using ApolloGraphQL.HotChocolate.Federation; public class Query { [ApolloAuthenticated] public IEnumerable GetMyProducts(Data repository) => repository.Products; } ``` -------------------------------- ### Configure @contact Directive for Subgraph Info in C# Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt This C# code configures the @contact directive to display subgraph contact information in Apollo Studio. It uses the [Contact] attribute on a custom schema class, specifying the team name, a URL, and a description. Dependencies include ApolloGraphQL.HotChocolate.Federation and ApolloGraphQL.HotChocolate.Federation.Two. ```csharp using ApolloGraphQL.HotChocolate.Federation; using ApolloGraphQL.HotChocolate.Federation.Two; [Contact("MyTeamName", "https://myteam.slack.com/archives/teams-chat-room-url", "send urgent issues to [#oncall](https://yourteam.slack.com/archives/oncall)")] public class CustomSchema : FederatedSchema { public CustomSchema() : base(FederationVersion.FEDERATION_25) { } } var builder = WebApplication.CreateBuilder(args); builder.Services .AddGraphQLServer() .AddApolloFederationV2(new CustomSchema()) .AddQueryType(); var app = builder.Build(); app.MapGraphQL(); app.Run(); // Generated GraphQL schema: // schema @contact( // name: "MyTeamName" // url: "https://myteam.slack.com/archives/teams-chat-room-url" // description: "send urgent issues to [#oncall](https://yourteam.slack.com/archives/oncall)" // ) { // query: Query // } ``` -------------------------------- ### ApolloAuthenticated Attribute Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Marks fields or types as requiring authentication. Requires Federation v2.5+. ```APIDOC ## ApolloAuthenticated Attribute The `[ApolloAuthenticated]` attribute marks fields or types as requiring authentication. Only available in Federation v2.5+. ### Example Usage: ```csharp public class Query { public Product? GetPublicProduct([ID] string id, Data repository) => repository.Products.FirstOrDefault(t => t.Id.Equals(id)); [ApolloAuthenticated] public IEnumerable GetMyProducts(Data repository) => repository.Products; } ``` ### Generated GraphQL Schema: ```graphql type Query { publicProduct(id: ID!): Product myProducts: [Product!]! @authenticated } ``` ``` -------------------------------- ### InterfaceObject Attribute Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Extends an interface defined in another subgraph without implementing all its types. Requires Federation v2.3+. ```APIDOC ## InterfaceObject Attribute The `[InterfaceObject]` attribute allows extending an interface defined in another subgraph without implementing all its types. Only available in Federation v2.3+. ### Example Usage: ```csharp // In another subgraph extending the interface: [Key("id")] [InterfaceObject] public class Product { [ID] public string Id { get; set; } public List Reviews { get; set; } // New field added to all Product implementations } ``` ### Generated GraphQL Schema: ```graphql type Product @key(fields: "id") @interfaceObject { id: ID! reviews: [String!]! } ``` ``` -------------------------------- ### Define NonResolvableKey for Stub Entities Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [NonResolvableKey] attribute defines an entity that is referenced by the current subgraph but cannot be resolved locally. This is useful for creating stubs of types owned by other subgraphs. ```csharp using ApolloGraphQL.HotChocolate.Federation; public class Review { public Review(Product product, int score) { Product = product; Score = score; } public Product Product { get; } public int Score { get; } } [NonResolvableKey("id")] public class Product { public Product(string id) { Id = id; } public string Id { get; } } ``` -------------------------------- ### Define Federated Entity with [Key] Attribute (C#) Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [Key] attribute marks a type as a federated entity, specifying its unique identifier field. This allows the entity to be uniquely identified and fetched across the supergraph. It requires the ApolloGraphQL.HotChocolate.Federation namespace. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("id")] public class Product { public Product(string id, string name, int price) { Id = id; Name = name; Price = price; } [ID] public string Id { get; } public string Name { get; } public int Price { get; } [ReferenceResolver] public static Product GetByIdAsync( string id, ProductRepository productRepository) => productRepository.GetById(id); } ``` -------------------------------- ### Configure @override Directive in C# Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt This C# code configures the @override directive to transfer field resolution responsibility from another subgraph in Hot Chocolate. It shows how to use the Override method on a field descriptor. Dependencies include HotChocolate.Types. ```csharp using HotChocolate.Types; public class ProductType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor .Key("id") .ResolveReferenceWith(t => ResolveProduct(default!, default!)); descriptor .Field(p => p.Description) .Override("LegacySubgraph"); } private static Product ResolveProduct(string id, ProductRepository repository) => repository.GetById(id); } // Generated GraphQL schema: // type Product @key(fields: "id") { // id: ID! // description: String @override(from: "LegacySubgraph") // } ``` -------------------------------- ### Extend Existing Entity with [Extends] Attribute (C#) Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [Extends] attribute signifies that a type is an extension of an entity defined in another subgraph. This allows for modularity and composition of federated services. It requires the ApolloGraphQL.HotChocolate.Federation namespace. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("upc")] [Extends] public class Product { public Product(string upc) { Upc = upc; } [External] public string Upc { get; } public Task> GetReviews(ReviewRepository repository) => repository.GetByProductUpcAsync(Upc); [ReferenceResolver] public static Product GetByIdAsync(string upc) => new(upc); } ``` -------------------------------- ### RequiresScopes Attribute Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt Restricts access to authenticated supergraph users with appropriate JWT scopes. Requires Federation v2.5+. ```APIDOC ## RequiresScopes Attribute The `[RequiresScopes]` attribute restricts access to authenticated supergraph users with appropriate JWT scopes. Only available in Federation v2.5+. ### Example Usage: ```csharp public class Query { [RequiresScopes(scopes: new string[] { "scope1, scope2", "scope3" })] [RequiresScopes(scopes: new string[] { "scope4" })] public Product? GetProduct([ID] string id, Data repository) => repository.Products.FirstOrDefault(t => t.Id.Equals(id)); [RequiresScopes(scopes: new string[] { "admin" })] public IEnumerable GetAllProducts(Data repository) => repository.Products; } ``` ### Generated GraphQL Schema: ```graphql type Query { product(id: ID!): Product @requiresScopes(scopes: [["scope1, scope2", "scope3"], ["scope4"]]) allProducts: [Product!]! @requiresScopes(scopes: [["admin"]]) } ``` ``` -------------------------------- ### Mark Field as Owned by Another Service with [External] (C#) Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [External] attribute indicates that a field is owned by a different service within the federated graph. These fields must be referenced in directives like @key, @requires, or @provides. It requires the ApolloGraphQL.HotChocolate.Federation namespace. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("id")] [Extends] public class User { public User(string id, string username) { Id = id; Username = username; } [External] public string Id { get; } [External] public string Username { get; } public Task> GetReviews(ReviewRepository repository) => repository.GetByUserIdAsync(Id); [ReferenceResolver] public static Task GetUserByIdAsync( string id, UserRepository repository) => repository.GetUserById(id); } ``` -------------------------------- ### Define Shareable Attribute for Multi-Subgraph Resolution Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [Shareable] attribute allows a field or type to be resolved by multiple subgraphs. This is a Federation v2 feature that enables more flexible schema composition. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("id")] public class Product { public Product(string id, string name, string description) { Id = id; Name = name; Description = description; } [ID] public string Id { get; } public string Name { get; } [Shareable] public string Description { get; } } [Shareable] public class SharedType { public string Description { get; set; } public string Name { get; set; } } ``` -------------------------------- ### Define Requires Attribute for External Field Dependencies Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [Requires] attribute specifies that a field depends on external data from other subgraphs. The router will fetch the required fields before resolving the target field. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("id")] public class Product { public Product(string id, int weight, int price) { Id = id; Weight = weight; Price = price; } [ID] public string Id { get; } [External] public int Weight { get; } [External] public int Price { get; } [Requires("weight price")] public int GetShippingEstimate() => Weight > 0 ? (Price / Weight) * 10 : 0; [ReferenceResolver] public static Product GetByIdAsync(string id) => new(id, 0, 0); } ``` -------------------------------- ### Define Inaccessible Attribute for Internal Fields Source: https://context7.com/apollographql/federation-hotchocolate/llms.txt The [Inaccessible] attribute hides a field from the public GraphQL schema while keeping it available for internal query planning. This is useful for internal-only data used by the router. ```csharp using ApolloGraphQL.HotChocolate.Federation; [Key("id")] public class User { public User(string id, string name, string internalId) { Id = id; Name = name; InternalId = internalId; } [ID] public string Id { get; } public string Name { get; } [Inaccessible] public string InternalId { get; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.