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的神奇之處。