Skip to main content

Hot Chocolate GraphQL Extending Object Types To Split Large Query And Mutation Classes

How GraphQL Extending Object Types Helps?:

  • In GraphQL two major operations are 'Queries' and 'Mutations'. 
  • So when we think from the code point of view all query-related logics maintain in one file and all mutation-related logics are maintained in another file. That's because GraphQL schema can't accept multiple 'Queries' and 'Mutations'.
  • But it is a very tedious job to maintain whole business logic in just 2 files(1Query and 1 Mutation file).
  • So to make it simple GraphQL has one technique called 'extend'. The 'extend' GraphQL schema gives us the flexibility to extend the main 'Query' or 'Mutation' which means we can have sub Queries or Mutation those derived from the parent.
  • On execution time everything merged as a single Query or Mutation schema.

Hot Chocolate GraphQL Extending Approaches:

Extending Object Types can be done in 2 different approaches:
  • Code First
  • Pure Code First

Code First:

In the code first approach, every c# class must have a mapping GraphQL class. So on runtime, these GraphQL classes will generate the schema. So in this approach, we need to learn about the GraphQL c# types. We have more control over coding like naming conventions, c# to object mapping, etc.

I had made a couple of blogs on the 'Code First' approach, if interested check the links below:

Pure Code First:

The Pure Code First technique so simple, here we only have c# class. So we have to register C# classes(Query and Mutation classes) in the startup under the GraphQL server. So on run time base on our c# class schema will be generated. This approach is very easy no need to learn any GraphQL terminology, and also we don't have full control over GraphQL code here because everything behind scenes taken care of is the GraphQL server.

Create A .Net5 Web API Project:

Our goal here is to understand Extending Objects Types are helpful to split the large Query and Mutation Classes. So we will implement a simple GraphQL application where we will create 2 Query classes and 2 Mutation classes with the help of Extending Objects Types technique. We also implement one class in 'Code First' and another class in the 'Pure Code First' approach for both Query and Mutation. So let's begin our GraphQL sample by creating .Net5 Web API application.

Note: Hot Chocolate GraphQL supports, coding can be done entirely in the 'Code First' approach or 'Pure Code First' or both combinations.

Install Hot Chocolate Graphql Nuget:

Package Manager Command:
Install-Package HotChocolate.AspNetCore -Version 11.0.9
.Net CLI Command:
dotnet add package HotChocolate.AspNetCore --version 11.0.9

Configure GraphQL Server And Endpoint:

Register GraphQL server in 'ConfigureServices()' method.
Startup.cs:(ConfigureService Method)
services.AddGraphQLServer();
Now configure GraphQL endpoint. The default path is '/graphql', if need we can change the path.
Startup.cs:(Configure Method)
app.UseEndpoints(endpoints =>
{
	endpoints.MapGraphQL();
	endpoints.MapControllers();
});

Register Root Query Name:

Startup.cs:
services.AddGraphQLServer()
.AddQueryType(q => q.Name("Query"))
Since our goal to have multiple query files, so we have to register GraphQL root query names like 'Query' with 'AddQueryType'. So this name will be used by all Extended Object Types query classes. On runtime, all queries will form a single query schema under the name we specified 'Query'. So we can use any name here, but the 'Query' name looks the most standard.

Create A GraphQL Query In Code First Approach:

Now first query file created in the code first approach. As we have discussed code first approach will have a C# class and its mapping GraphQL class.

Now let's create a C# query class which can be called a Resolver. The 'Resolver' means it contains all query methods like fetching data from the database or any data source. So let's add the folder 'QueryResolvers' and then add c# query file like 'CountryResolver.cs'.
QueryResolvers/CountryResolver.cs:
namespace GQL_Splitfiles.QueryResolvers
{
    public class CountryResolver
    {
        public string GetHomeCounry()
        {
            return "India";
        }
    }
}
  • Here I have a method that returns a simple string as a result.
Now let's add a new folder 'QueryTypes', in this folder we will create all GraphQL classes. Now we have to create a mapping class for 'CountryResolver.cs' like 'CountryTypeExtension.cs'.
QueryTypes/CountryTypeExtension.cs:
using GQL_Splitfiles.QueryResolvers;
using HotChocolate.Types;

namespace GQL_Splitfiles.QueryTypes
{
    public class CountryTypeExtension: ObjectTypeExtension
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.Name("Query");

            descriptor.Field("GetHomeCounry")
            .ResolveWith<CountryResolver>(_ => _.GetHomeCounry())
            .Type<StringType>()
            .Name("HomeCountry");
            
        }
    }
}
  • By inheriting 'HotChocolate.Types.ObjectTypeExtension' makes our 'CountryTypeExtension' as GraphQL extended query.
  • (Line: 10) We are registered "Query" as name to 'CoutryTypeExtension'. So in every class that inherits 'ObjectTypeExtension' should register with the name "Query"(the name that registered in the startup file).
  • (Line: 12) Every method in the normal C# class(CountryResolver.cs) must be registered as 'Field' in ObjectTypeExtension class(CountryResolver.cs).
  • (Line: 13) Using 'ResolveWith' method register the method like 'GetHomeCounry()'.
  • (Line: 14) 'SrtingType' is GraphQL type. The 'Type<>' here used to specify the GraphQL type that equivalent to the resolver method registered.
  • (Line: 15) The 'Name()' to define the name of our 'Field'. This name will be used by the clients for querying the GraphQL endpoint.
Register 'CountryTypeExtension.cs' in startup.cs.
Startup.cs:
services.AddGraphQLServer()
.AddQueryType(q => q.Name("Query"))
.AddType<CountryTypeExtension>();
Now check the GraphQL endpoint and its result.

Create A GraphQL Query In Pure Code First Approach:

Now, 2nd Query file we will implement in the Pure Code First approach. This technique is very simple, a single resolver class is enough.

Now let's create a new resolver file like 'PetResolver.cs'.
QueryResolvers/PetResolver.cs:
using HotChocolate.Types;

namespace GQL_Splitfiles.QueryResolvers
{
    [ExtendObjectType(Name="Query")]
    public class PetResolver
    {
        public string YourPet()
        {
            return "Dog";
        }
    }
}
  • The 'HotChocolate.Types.ExtendObjectType' attribute with name "Query", this attribute makes our class 'PetResolver.cs' is extended from the query.
  • Now we don't need any mapper of GraphQL class. Because the GraphQL server will automatically generate a query scheme from our resolver class in Pure Code First approach.
In the final step, we have to register our resolver class 'PetResolver.cs' in 'Startup.cs'.
Startup.cs:
services.AddGraphQLServer()
.AddQueryType(q => q.Name("Query"))
.AddType<CountryTypeExtension>()
.AddType<PetResolver>();
Here in Pure Code First approach, the method name should be in the pascal case while querying. Here in the resolver class method name 'YourPet' need to be written like 'yourPet' while querying.
So we have successfully split the Query classes using Extending Object Types.

Add Root Mutation Name:

Startup.cs:
services.AddGraphQLServer()
.AddQueryType(q => q.Name("Query"))
	.AddType<CountryTypeExtension>()
	.AddType<PetResolver>()
.AddMutationType(m => m.Name("Mutation"))
Here our goal is to split mutation files, so we have to create a root mutation name like 'Mutation' in the 'AddMutation' method. So this name should be declared in every individual extended mutation file so that all mutation will be combined and generated as a single mutation scheme on runtime.

Create A GraphQL Mutation In Code First Approach:

Now first mutation file created using Code First. So we already discussed in Code First approach every c# class will a mapping GraphQL class.

Mutation means saving or updating data to the database. So we should have a payload object to send data to the server. So let's create a folder like 'Models' and add a file 'CountryModel.cs'.
Models/CountryModel.cs:
namespace GQL_Splitfiles.Models
{
    public class CountryModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
Now for the 'CountryModel.cs' file, we should have a GraphQL class. So let's create a folder like 'InputTypes' and add a  file like 'CountryInput.cs'.
InputTypes/CountryInput.cs:
using GQL_Splitfiles.Models;
using HotChocolate.Types;

namespace GQL_Splitfiles.InputTypes
{
    public class CountryInput: InputObjectType<CountryModel>
    {
        protected override void Configure(IInputObjectTypeDescriptor<CountryModel> descriptor)
        {
            descriptor.Name("CountryInput");
            descriptor.Field(_ => _.Id)
            .Type<IntType>()
            .Name("Id");

            descriptor.Field(_ => _.Name)
            .Type<StringType>()
            .Name("Name");
        }
    }
}
  • The 'CountryInput' should Inherit 'InputObjectType<T>'. The 'InputObjectType' is for input data from the client. Inside of the 'CounryInput' we need to register all required properties as 'Fields'. The value in the method 'Name()' will be used by the client while consuming the mutation endpoint. 
Now we will create a Mutation resolver class that contains a method to save data to the database. So let's create a folder 'MutationResolver' and add a file like 'CountryMutateResolver.cs'.
MutationResolver/CountryMutateResolver.cs:
using GQL_Splitfiles.Models;

namespace GQL_Splitfiles.MutationResolvers
{
    public class CountryMutateResolver
    {
        public string SaveCountry(CountryModel model)
        {
            // implement logic to save to database or datasource
            return model.Name;
        }
    }
}
Now we should have GraphQL class for 'CoutnryMutateResolver.cs'. So let's create a folder 'MutationTypes' and add a file 'CountryMutateTypeExtension'.
MutationTypes/CountryMutateTypeExtension.cs:
using GQL_Splitfiles.InputTypes;
using GQL_Splitfiles.MutationResolvers;
using HotChocolate.Types;

namespace GQL_Splitfiles.MutationTypes
{
    public class CountryMutateTypeExtension: ObjectTypeExtension
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.Name("Mutation");

            descriptor.Field("SaveCountry")
            .ResolveWith<CountryMutateResolver>(m => m.SaveCountry(default))
            .Argument("model", _ => _.Type<CountryInput>())
            .Type<StringType>()
            .Name("SaveCountry");
        }
    }
}
  • (Line: 7) To create an extended mutation, the class must inherit the 'HotChocolate.Types.ObjectTypeExtnesion'.
  • (Line: 11) Extended mutation class name as 'Mutation' which should match with the name of the root mutation registered in a startup.
  • (Line: 14) Register our resolver method 'SaveCountry()' from 'CountryMutateResolver.cs'.
  • (Line: 15) We should register 'SaveCountry()' method input parameters here using 'Argument()' method.
  • (Line: 16) GraphQL type whose type equivalent to c# type of  'SaveCountry()' method return type.
  • (Line: 17) GraphQL 'name' for our c# 'SaveCountr()' method. This name will be used on the client-side to invoke mutation.
Now register our 'CoutnryMutateTypeExtension.cs' file at startup.cs.
Startup.cs:
services.AddGraphQLServer()
.AddQueryType(q => q.Name("Query"))
	.AddType<CountryTypeExtension>()
	.AddType<PetResolver>()
.AddMutationType(m => m.Name("Mutation"))
	.AddType<CountryMutateTypeExtension>();
Now let's frame the mutation.
Mutation:
mutation ($modelInput:CountryInput){
  SaveCountry(model:$modelInput)
}
  • The 'mutation' keyword just represents the action type.
  • The '$modelInput' is GraphQL variable. The 'CountryInput' is type of our $'modelInput'. The 'CountryInput' should match with the value of the 'Name' method inside of the 'CountryInput.cs'.
  • The 'SaveCounry' is the registered name of 'Field' in the 'CounryMutateTypeExtension' class. The 'model' is the input variable registered at the 'Argument' method.
variable:
{
  "modelInput":{
    "Id":100,
    "Name":"India"
  }
}
  • Here payload should be passed as properties of an object whose name matches with 'variable in mutation. Here we just remove '$' from the variable name.
Now test our mutation as below.

Create GraphQL Mutation In Pure Code First Approach:

Now, the 2nd GraphQL Mutation file creating using the Pure Code First Approach. We know that in Pure Code First approach we don't need to create the GraphQL classes.

So first let's create a payload class like 'PoetModel.cs'.
Models/PoetModel.cs:
namespace GQL_Splitfiles.Models
{
    public class PetModel
    {
        public int Id{get;set;}
        public string Name{get;set;}
    }
}
Now we have to create our Mutation resolver class.
MutaionResolvers/PetMutateResolver.cs:
using GQL_Splitfiles.Models;
using HotChocolate.Types;

namespace GQL_Splitfiles.MutationResolvers
{
    [ExtendObjectType(Name="Mutation")]
    public class PetsMutateResolver
    {
        public string SavePet(PetModel model)
        {
            //logic save data to database
            return model.Name;
        }
    }
}
  • The 'HotChocolate.Types.ExtendObjectType' make the decorated class extend class of  'Mutation'
Now register our 'PetMutateResolver' in 'Startup.cs' file.
Startup.cs:
services.AddGraphQLServer()
.AddQueryType(q => q.Name("Query"))
	.AddType<CountryTypeExtension>()
	.AddType<PetResolver>()
.AddMutationType(m => m.Name("Mutation"))
	.AddType<CountryMutateTypeExtension>()
	.AddType<PetsMutateResolver>();
Now test the mutation.
So we finally split mutation into multiple files.

Video Session:

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information about splitting Query and Mutation files in Hot Chocolate GraphQL. I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:

Comments

  1. Sir, I am using Pure code first approach. I have two question
    1 - I added [ExtendObjectType(Name = "Query")] attribute on my resolver. Everything working fine. But I am getting
    Warning CS0618 'ExtendObjectTypeAttribute.Name.set' is obsolete: 'Use the new constructor.' Can you suggest how I can fix this?

    2 - I have two resolver GetEmployeeInfoIncludingSalary and
    GetEmployeeInfoWithoutSalary both are using same entity Employee.
    I created EmployeeType : ObjectType class and in configure method i ignored salary field. so eveything worked for GetEmployeeInfoWithoutSalary.

    But when I am calling GetEmployeeInfoIncludingSalary method I am getting error Salary field does not exist. Can we create ObjectType at reslover level so i can inject specific type for specific resolver?

    ReplyDelete
    Replies
    1. Please Ignore first question, I got solution [ExtendObjectType(name: "Query")]

      Delete
    2. Your proposed solution of [ExtendObjectType(name: "Query")] doesn't get rid of the obsolete message for myself. Any other alternatives? The message about it being obsolete doesn't give me enough info about what the new format is.

      Delete
    3. Try to replace 'ExtendObjectType' to 'System.Type'

      check the change log:
      https://github.com/ChilliCream/hotchocolate/blob/develop/CHANGELOG.md

      Delete
  2. How to handle async type of function in resolver?

    ReplyDelete

Post a Comment

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually