Dotnet api graphql linux

From bibbleWiki
Jump to navigation Jump to search

Creating a Project

Copy the project from RAID array

Sorry no help here

Add the packages

dotnet add package GraphQL

Create Database

Change the connection string

"CarvedRock": "Server=.;Database=CarvedRock;Trusted_Connection=False;User Id=test;Password=nottherealone"

Update the database

dotnet ef database update

Run the Site

To the site and look at https://localhost:5001/ui/playground

Creating a Schema

Create a Product Graph Type

Create Fields based on Meta Fields within ObjectGraphType

    public class ProductType: ObjectGraphType<Product>
    {
        public ProductType()
        {
            Field(t => t.Id);
            Field(t => t.Name).Description("The name of the product");
            Field(t => t.Description);
        }
    }

Create a Query

Create a Query which looks in the repository (DB) and gets all of the products.

    public class CarvedRockQuery: ObjectGraphType
    {
        public CarvedRockQuery(ProductRepository productRepository)
        {
            Field<ListGraphType<ProductType>>(
                "products", 
                resolve: context => productRepository.GetAll()
            );
        }
    }

Create a Schema for the Carved Rock Query

This holds the queries the schema supports. In our case the CarvedRockQuery created above

    public class CarvedRockSchema: Schema
    {
        public CarvedRockSchema(IDependencyResolver resolver): base(resolver)
        {           
            Query = resolver.Resolve<CarvedRockQuery>();
        }
    }

Configuring ASP .NET Core

In the Startup, Add the dependency resolver to the services, add the Schema and GraphQL configuring options.

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddScoped<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));

            services.AddScoped<CarvedRockSchema>();

            services.AddGraphQL(o => { o.ExposeExceptions = false; })
                .AddGraphTypes(ServiceLifetime.Scoped);

Add the GraphQL to the middleware

        public void Configure(
            IApplicationBuilder app, 
            CarvedRockDbContext dbContext)
        {
           app.UseGraphQL<CarvedRockSchema>();
           app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());

Creating a GraphQL API

Adding Scalar Type

Create the enum

    public enum ProductType
    {
        Boots,
        ClimbingGear,
        Kayaks
    }

Derive a GraphQL type using this Enum add the Name and description

    public class ProductTypeEnumType: EnumerationGraphType<Data.ProductType>
    {
        public ProductTypeEnumType()
        {
            Name = "Type";
            Description = "The type of product";
        }
    }

Lets add that to our Product type

    public class ProductType: ObjectGraphType<Product>
    {
        public ProductType()
        {
            Field(t => t.Id);
...
            Field<ProductTypeEnumType>("Type", "The type of product");
...

Adding Complex Type

Steps Required to Add a Complex Type

  • Create a class
  • Add a Accessor to the DbContext
  • Add a GraphQL Type
  • Create a Repository Class
  • Add the Graph QL Type to the Product

Create the class

    public class ProductReview
    {
        public int Id {get; set;}
        public int ProductId {get; set;}
        public Product Product {get; set;}
        [StringLength(200), Required]
        public string Title {get; set;}
        public string Review {get; set;}
    }

Add a Accessor to the DbContext

    public class CarvedRockDbContext: DbContext
    {
...
        public DbSet<ProductReview> ProductReviews { get; set; }
    }

Add a GraphQL Type

    public class ProductReviewType : ObjectGraphType<ProductReview>
    {
        public ProductReviewType()
        {
            Field(t => t.Id);
            Field(t => t.Title);
            Field(t => t.Review);
        }
    }

Create a Repository Class

    public class ProductReviewRepository
    {
        private readonly CarvedRockDbContext _dbContext;

        public ProductReviewRepository(CarvedRockDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<IEnumerable<ProductReview>> GetForProduct(int productId)
        {
            return await _dbContext.ProductReviews.Where(pr => pr.ProductId == productId).ToListAsync();
        }

        public async Task<ILookup<int, ProductReview>> GetForProducts(IEnumerable<int> productIds)
        {
            var reviews = await _dbContext.ProductReviews.Where(pr => productIds.Contains(pr.ProductId)).ToListAsync();
            return reviews.ToLookup(r => r.ProductId);
        }
    }

Add the Graph QL Type to the Product

    public class ProductType : ObjectGraphType<Product>
    {
        public ProductType(ProductReviewRepository reviewRepository)
        {
            Field(t => t.Id);
            Field(t => t.Name).Description("The name of the product");
...
            Field<ListGraphType<ProductReviewType>> (
                "Reviews",
                resolve : context =>  reviewRepository.GetForProduct(context.Source.Id)
            );