Fork me on GitHub

GraphQL:DataLoader的神奇

  GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。
                                        ——出自 https://graphql.cn

  Rest API中,一个api,通过参数,只能获取这个参数范围内的数据,如果想获取别的参数范围内数据,就得再次调用,比如GetStudent(id),想获取多个Student,就得多次调用,把替换id就可以,GraphQL的其中优势就是,在一次请求中,返回你所要的数据,减少请求,就像请求聚合。

using GreenDonut;
using HotChocolate;
using HotChocolate.Data;
using HotChocolate.Fetching;
using HotChocolate.Resolvers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace GraphQLDemo04
{
    public class Startup
    {
        /// <summary>
        /// Persons只是假装数据库
        /// </summary>

        public static List<Result<Student>> Persons = new List<Result<Student>>();

        public void ConfigureServices(IServiceCollection services)
        {
            for (int i = 0; i < 200; i++)
            {
                //NameCreater.GetFullName只是随机生成人的名称
                var student = new Student { Id = i, Tel = "13453467" + i.ToString("D3"), Name = NameCreater.GetFullName() };
                var result = Result<Student>.Resolve(student);
                Persons.Add(result);
            }

            services
                .AddGraphQLServer()
                .AddQueryType<Query>()
                ;
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGraphQL();
            });
        }
    }

    /// <summary>
    /// 查询类
    /// </summary>
    public class Query
    {
        public Task<Student> GetStudent(int id, [DataLoader] StudentDataLoader loader)
        {
            return loader.LoadAsync(id);
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class StudentDataLoader : DataLoaderBase<int, Student>
    {
        public StudentDataLoader(IBatchScheduler scheduler) : base(scheduler)
        {
        }
        protected override ValueTask<IReadOnlyList<Result<Student>>> FetchAsync(IReadOnlyList<int> keys, CancellationToken cancellationToken)
        {
            return new ValueTask<IReadOnlyList<Result<Student>>>(Startup.Persons.Where(s => keys.Contains(s.Value.Id)).ToList());
        }

    }
    /// <summary>
    /// 学生
    /// </summary>
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Tel { get; set; }
    }
}

代码中的StudentDataLoader就是来完成请求聚合的。
请求条件如下,请求四个id=10,id=20,id=30,id=40

{
    a:student(id:10){
        id
        name
        tel
        }
    b:student(id:20){
        id
        name
        tel
        }
    c:student(id:30){
        id
        name
        tel
        }
    d:student(id:40){
        id
        name
        tel
        }
}

返回结果:

 

   调置断点,可以看到监视里的keys是四个元素,一次请求来的,DataLoader会把条件id分离出来提供给我们,方便进行后端数据查询,这也是便是DataLoader的神奇之处。

 

 

  想要更快更方便的了解相关知识,可以关注微信公众号 
 

 

 

posted @ 2022-02-01 15:45  桂素伟  阅读(84)  评论(0编辑  收藏  举报