Simplify API Creation for GraphQL Models using Hot Chocolate in .NET

52 Views Asked by At

I'm relatively new to GraphQL. I've previously worked with tools like Hasura, Orchard Core, and Strapi, where the process of creating tables automatically generates basic APIs (such as GET, GETbyID, POST, DELETE) for CRUD operations. Now, I'm seeking guidance on how to achieve similar functionality in GraphQL using Hot Chocolate in a .NET environment.

In my current project, I'm dealing with six objects that require basic querying functionalities. However, I find the manual setup quite confusing and challenging to maintain. Below is an excerpt of my current implementation:

using Microsoft.EntityFrameworkCore;
namespace BackEnd
{
    public class Query
    {
        public async Task<List<Question>> GetQuestions(AppDbContext dbContext)
        {
            return await dbContext.Questions.ToListAsync();
        }
        
        public async Task<List<Answer>> GetAnswers(AppDbContext dbContext)
        {
            return await dbContext.Answers.ToListAsync();
        }
        
        public async Task<List<User>> GetUsers(AppDbContext dbContext)
        {
            return await dbContext.Users.ToListAsync();
        }
        
        public async Task<List<House>> GetHouse(AppDbContext dbContext)
        {
            return await dbContext.House.ToListAsync();
        }
        
        public async Task<List<Cat>> GetCats(AppDbContext dbContext)
        {
            return await dbContext.Cats.ToListAsync();
        }
        
        public async Task<List<Dogs>> GetDogs(AppDbContext dbContext)
        {
            return await dbContext.Dogs.ToListAsync();
        }
    }
}

I would appreciate any advice or guidance on how to streamline this process, perhaps utilizing Hot Chocolate's features or any other recommended approaches within the .NET ecosystem. Thank you!

I tried to improve the code structure and clarity for easier maintenance. I expected to provide a more organized and efficient solution for querying GraphQL models using Hot Chocolate in a .NET environment. The changes made include reformatting the code for better readability, providing a clear explanation of the issue, and seeking advice on optimizing the implementation.

1

There are 1 best solutions below

0
iCodeSometime On

Here's a simplified example to get you started...

Helper method to create an object type

public static ObjectTypeExtension CreateTypeExtensionAsync()
{
    var typeDefinition = new ObjectTypeDefinition(nameof(OperationType.Query)); // Adding these fields directly on Query

    foreach (var prop in typeof(AppDbContext).GetProperties())
    {
        typeDefinition.Fields.Add(
            new ObjectFieldDefinition(
                $"{prop.Name}", // the name of the field we're adding
                type: TypeReference.Parse("String!"), // the type we're returning.. it's likely a list of the first generic argument for the prop - make sure you add the type to the builder if you're not using it elsewhere
                pureResolver: ctx => prop.Name)); // actual resolver logic here
    }

    return ObjectTypeExtension.CreateUnsafe(typeDefinition);
}

Then at startup

var dynamicTypeExtension = CreateTypeExtensionAsync();
builder.AddTypeExtension(dynamicType);

This adds each property with a resolver that just returns the property name (as an example).

You can use the PropertyInfo get the reelevant DbSet from an AppDb instance to call your methods on.