Arash
Arash

Reputation: 3688

splitting query type in hot chocolate qraphql in asp.net core

This is my config in startup .cs

 .AddGraphQLServer()
                   .AddQueryType<Query>()
                   .AddType<CustomerQuery>()
                   .AddType<ProductQuery>()
                   .AddType<CustomerType>()
                   .AddType<ProductType>()
                   .AddFiltering()
                   .AddSorting();

I have two class separate query class

[ExtendObjectType(Name = "Query")]
public class CustomerQuery
{
    private readonly IRepository<Customer> customerRepository;

    public CustomerQuery(IRepository<Customer> customerRepository)
    {
        this.customerRepository = customerRepository;
    }
    public IQueryable<Customer> customers() => customerRepository.Table.Where(i=>i.Active==true);
    public Customer customer (string id) => customerRepository.GetById(Convert.ToInt16(id));

}

[ExtendObjectType(Name = "Query")]
public  class ProductQuery
{
    private readonly IRepository<Product> productRepository;

    public ProductQuery(IRepository<Product> productRepository)
    {
        this.productRepository = productRepository;
    }

    public IQueryable<Product> Products() => productRepository.Table.AsQueryable();
}

I have two other class which configure ProductQuery and CustomerQuery

public class ProductQueryType:ObjectType<ProductQuery>
{
    protected override void Configure(IObjectTypeDescriptor<ProductQuery> descriptor)
    {
        descriptor
             .Field(f => f.Products())
             .UsePaging()
             .UseFiltering()
             .UseSorting()
             .Type<ProductType>();
             
    }
}

public class CustomerQueryType:ObjectType<CustomerQuery>
{
    protected override void Configure(IObjectTypeDescriptor<CustomerQuery> descriptor)
    {
        descriptor
            .Field(f => f.customers())
            .UsePaging()
            .UseFiltering()
            .UseSorting()
            .Type<CustomerType>();
    }
}

I cant add these two configuration in my startup.cs , it makes graphl endpoint some error , how can i add query configuration pipeline ?

Upvotes: 0

Views: 2058

Answers (1)

ademchenko
ademchenko

Reputation: 670

To be honest, there is a big number of misconceptions in your code, so, I decided to completely rewrite it and provide you with a working starting point.

using System;
using System.Linq;
using HotChocolate;
using HotChocolate.Types;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Ademchenko.GraphQLWorkshop
{
    public interface IRepository<out T>
    {
        IQueryable<T> Table { get; }

        T GetById(short id);
    }

    public class CustomerRepository : IRepository<Customer>
    {
        private readonly Customer[] _staticCustomers = {
            new Customer {Active = true, FirstName = "FooCustomer", Id = 1},
            new Customer {Active = true, FirstName = "BarCustomer", Id = 2},
        };

        public IQueryable<Customer> Table => _staticCustomers.AsQueryable();

        public Customer GetById(short id) => _staticCustomers.Single(c => c.Id == id);
    }

    public class ProductRepository : IRepository<Product>
    {
        private readonly Product[] _staticProducts = {
            new Product {Name = "FooProduct", Id = 3},
            new Product {Name = "BarOfHotChocolateProduct", Id = 4},
        };

        public IQueryable<Product> Table => _staticProducts.AsQueryable();

        public Product GetById(short id) => _staticProducts.Single(c => c.Id == id);
    }

    public class CustomerQuery
    {
        private readonly IRepository<Customer> _customerRepository;

        public CustomerQuery([Service] IRepository<Customer> customerRepository) => _customerRepository = customerRepository;

        public IQueryable<Customer> Customers() => _customerRepository.Table.Where(i => i.Active);

        public Customer Customer(Int16 id) => _customerRepository.GetById(id);
    }

    public class CustomerQueryType : ObjectTypeExtension<CustomerQuery>
    {
        protected override void Configure(IObjectTypeDescriptor<CustomerQuery> descriptor) =>
            descriptor.Name("Query").Field(f => f.Customers()).UsePaging().UseFiltering().UseSorting();
    }

    public class ProductQuery
    {
        private readonly IRepository<Product> _productRepository;

        public ProductQuery([Service] IRepository<Product> productRepository) => _productRepository = productRepository;

        public IQueryable<Product> Products() => _productRepository.Table.AsQueryable();
    }


    public class ProductQueryType : ObjectTypeExtension<ProductQuery>
    {
        protected override void Configure(IObjectTypeDescriptor<ProductQuery> descriptor) =>
            descriptor.Name("Query").Field(f => f.Products()).UsePaging().UseFiltering().UseSorting();
    }


    public class Customer
    {
        public Int16 Id { get; set; }

        public string FirstName { get; set; }

        public bool Active { get; set; }
    }

    public class Product
    {
        public Int16 Id { get; set; }

        public string Name { get; set; }
    }

    public class Startup
    {
        public IConfiguration Configuration { get; }
        
        public Startup(IConfiguration configuration) => Configuration = configuration;

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSingleton<IRepository<Customer>, CustomerRepository>();
            services.AddSingleton<IRepository<Product>, ProductRepository>();

            services
                .AddGraphQLServer()
                .AddQueryType(t => t.Name("Query"))
                .AddType<ProductQueryType>()
                .AddType<CustomerQueryType>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) =>
            app.UseRouting().UseEndpoints(endpoints => endpoints.MapGraphQL());
    }
}

If you manage to compile (with HotChocolate v.11 libs) and run it you will be able to open Balana Cake Pop and run the following query:

{
  products(first: 1, order_by: {id: ASC}, where: {name_contains: "Foo"})
  {
    pageInfo
    {
      startCursor
      hasNextPage
    }
    nodes
    {
      id
      name
    }
 }
 customers(first: 1, where: {firstName: "BarCustomer"})
 {
   pageInfo
   {
     startCursor
     hasPreviousPage
     hasNextPage
   }
   nodes
   {
     id
     firstName
     active
   }
 }
 customer(id: 1)
 {
   id
   firstName   
 }
}

The system will return the following answer:

{
  "data": {
    "products": {
      "pageInfo": {
        "startCursor": "MA==",
        "hasNextPage": false
      },
      "nodes": [
        {
          "id": 3,
          "name": "FooProduct"
        }
      ]
    },
    "customers": {
      "pageInfo": {
        "startCursor": "MA==",
        "hasPreviousPage": false,
        "hasNextPage": false
      },
      "nodes": [
        {
          "id": 2,
          "firstName": "BarCustomer",
          "active": true
        }
      ]
    },
    "customer": {
      "id": 1,
      "firstName": "FooCustomer"
    }
  }
}

Hope, this helps!

Upvotes: 4

Related Questions