Software Engineer Encyclopedia
0%
Domain 03 · Backend Engineering & Web Development · Pillar

GraphQL بالعمق مع Hot Chocolate: وإمتى تختاره بدل REST

GraphQL in Depth with Hot Chocolate

GraphQL كعقد: schema وtypes وqueries/mutations/subscriptions، الـ execution model وليه مشكلة N+1 أخطر هنا، DataLoaders وbatch resolvers، projections مع EF Core، الـ pagination (cursor connections)، الـ authorization، حماية السيرفر (depth/complexity/persisted operations)، الـ errors، والـ versioning — بـ Hot Chocolate 16 على ASP.NET Core، ومقارنة صريحة بـ REST وgRPC.

  • Intermediate
  • ~9 min read
  • 15 sections
  • 8 code examples
  • 2 diagrams
  • 5 questions
  • Priority L2 · Essential
  • Hot Chocolate 16.x (released May 2026) · .NET 8/9/10 · EF Core 10 — APIs reviewed 2026-11-18 against chillicream.com; earlier majors (13–15) differ in places

بعد الدرس ده هتقدر

  • تشرح GraphQL كـ typed schema + query language وتقرأ وتكتب queries وmutations وfragments وvariables
  • تبني GraphQL server بـ Hot Chocolate: query/mutation types، EF Core integration، DI
  • تفهم الـ resolver execution model وتحل N+1 بـ DataLoaders أو batch resolvers
  • تطبق projections/filtering/sorting وcursor pagination بأمان
  • تحمي السيرفر: depth/complexity limits، persisted operations، introspection policy، authorization per field
  • تصمم الـ errors والـ evolution (deprecation بدل versions)
  • تقرر بموضوعية بين GraphQL وREST وgRPC

المتطلبات قبل ما تبدأ

01

GraphQL بيحل إيه؟

The problem GraphQL solves
Basics

شاشة dashboard في Angular محتاجة: بيانات المستخدم، آخر 5 مستندات بعنوانها بس، وعدد الأسئلة في كل مستند. في REST يا إما 3 requests (أو N+1 requests من الـ client)، يا إما endpoint مخصص للشاشة دي بالذات (وكل شاشة جديدة = endpoint جديد). GraphQL بيقلب العلاقة: السيرفر بيعرض schema مكتوبة بأنواع، والـ client بيطلب بالظبط الشكل اللي محتاجه في request واحد.

RESTAngularGET /meGET /documents?take=5GET /documents/{id}/stats ×5GraphQLAngularPOST /graphql{ me { name } documents(first:5){ title questionCount }}REST: simple caching per URL, mature tooling, but over/under-fetching and many round trips for rich screens.GraphQL: exact shape, one round trip, strong typing — but caching, cost control and N+1 move to the server.
REST: several fixed resources; GraphQL: one endpoint, the client describes the shape
02

اللغة نفسها: schema و queries و mutations

Schema and operations
Basics
GraphQLschema (SDL) — generated from C# types in Hot Chocolate
type Query {
  me: User!
  documents(first: Int, after: String, where: DocumentFilterInput, order: [DocumentSortInput!]): DocumentsConnection
  document(id: ID!): Document
}
type Mutation {
  askQuestion(input: AskQuestionInput!): AskQuestionPayload!
}
type Document {
  id: ID!
  title: String!
  updatedAt: DateTime!
  status: DocumentStatus!
  questionCount: Int!
  owner: User!
}
enum DocumentStatus { QUEUED PROCESSING READY FAILED }
GraphQLan operation with variables and a fragment
query Dashboard($first: Int = 5) {
  me { name plan }
  documents(first: $first, order: [{ updatedAt: DESC }]) {
    nodes { ...DocCard }
    pageInfo { hasNextPage endCursor }
  }
}
fragment DocCard on Document { id title status questionCount }
  • Types والـ nullability: String! = مش null أبدًا. ده عقد: لو resolver رجع null لحقل non-null، الـ null بيتنقل للأب (ممكن يمسح جزء كبير من الرد). صمّم الـ nullability بوعي.
  • Query مقابل Mutation: الـ queries ممكن تتنفذ fields فيها بالتوازي؛ الـ mutations في المستوى الأعلى بتتنفذ بالترتيب.
  • Subscriptions: events live عبر WebSockets/SSE (شبه SignalR بس بنفس الـ schema).
  • Introspection: الـ schema بتوصف نفسها، فالأدوات (Nitro/Banana Cake Pop، codegen) بتولّد types للـ client تلقائيًا.
03

سيرفر Hot Chocolate على ASP.NET Core

Building the server
Practical
Bashpackages (versions: use the current 16.x)
dotnet add package HotChocolate.AspNetCore
dotnet add package HotChocolate.Data.EntityFramework
C#Program.cs + types (annotation-based)
builder.Services.AddDbContextPool<AppDb>(o => o.UseNpgsql(cs));
builder.Services
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .AddMutationType<Mutation>()
    .AddProjections().AddFiltering().AddSorting()
    .AddAuthorization()
    .ModifyCostOptions(o => { o.MaxFieldCost = 2_000; o.MaxTypeCost = 2_000; })   // cost analysis (see Security)
    .ModifyRequestOptions(o => o.IncludeExceptionDetails = builder.Environment.IsDevelopment());

var app = builder.Build();
app.UseAuthentication(); app.UseAuthorization();
app.MapGraphQL();                                         // /graphql (+ Nitro IDE in development)

public sealed class Query
{
    [Authorize]
    [UsePaging(MaxPageSize = 50, IncludeTotalCount = true)]
    [UseProjection, UseFiltering, UseSorting]
    public IQueryable<Document> GetDocuments(AppDb db, [Service] ITenantContext t)
        => db.Documents.Where(d => d.TenantId == t.TenantId);           // tenant scoping in the resolver root (plus EF query filter)

    [Authorize]
    public Task<Document?> GetDocument(Guid id, AppDb db, [Service] ITenantContext t, CancellationToken ct)
        => db.Documents.SingleOrDefaultAsync(d => d.Id == id && d.TenantId == t.TenantId, ct);
}

أسماء الـ attributes والـ options (مثلًا cost options، الـ projections) اتغيرت بين majors؛ الكود ده على شكل 15/16 — راجع docs الـ 16 لنسختك.

الـ IQueryable + middleware: UseProjection بيحوّل الحقول المطلوبة في الـ query لـ Select في SQL (ما بيجيبش أعمدة مش مطلوبة)، و UseFiltering/UseSorting بيترجموا where/order لـ LINQ. الترتيب مهم: paging ← projection ← filtering ← sorting (من برّه لجوّه زي ما فوق).

04

الـ execution model ومشكلة N+1

Resolvers and the N+1 problem
Deep dive

كل field ليه resolver. لو الـ query طلبت 50 مستند وكل مستند owner، الـ resolver بتاع owner بيتنادى 50 مرة — لو كل مرة بيعمل query ← 51 query. في REST الـ N+1 بيبان في endpoint واحد؛ في GraphQL الـ client بيقدر يركّب queries بتعمل N+1 في أماكن ما توقعتهاش.

naivedocuments (50)SELECT user WHERE id=1SELECT user WHERE id=2… ×50DataLoader / batch resolverdocuments (50)collect idsSELECT … WHEREid IN (…50)51 round trips → 2 round trips, and a per-request cache: the same user is loaded once.
Without batching every parent triggers a query; a DataLoader collects keys in one tick and loads them in one query
C#DataLoader (source-generated style) and its use in a type extension
public static class UserDataLoaders
{
    [DataLoader]
    public static async Task<IReadOnlyDictionary<Guid, User>> GetUserByIdAsync(
        IReadOnlyList<Guid> ids, AppDb db, CancellationToken ct)
        => await db.Users.Where(u => ids.Contains(u.Id)).ToDictionaryAsync(u => u.Id, ct);   // one query for all keys
}

[ExtendObjectType<Document>]
public sealed class DocumentExtensions
{
    public Task<User> GetOwnerAsync([Parent] Document doc, IUserByIdDataLoader users, CancellationToken ct)
        => users.LoadRequiredAsync(doc.OwnerId, ct);
}
// Hot Chocolate 16 also introduces batch resolvers: one resolver receives all parent objects for a field at once.

الربط: نفس المشكلة ونفس الحل (batching + projection) في EF Core: Loading & N+1. الفرق إن هنا لازم الحل يكون في كل resolver لأنك ما تعرفش الـ clients هيطلبوا إيه.

05

Pagination: cursor connections

Paging the right way
Practical

Hot Chocolate بيطبق Relay Connections: first/after و last/before مع edges { cursor node } و pageInfo. الـ cursor مبني على الترتيب، فده keyset pagination مش offset — ثابت مع البيانات المتغيرة وأسرع في الصفحات العميقة (نفس منطق REST pagination).

  • حدد MaxPageSize دايمًا؛ وإلا client يطلب first: 100000.
  • totalCount بيعمل COUNT(*) — مكلف على جداول كبيرة؛ فعّله بس لو الـ UI محتاجه.
  • الترتيب لازم يكون حتمي (ضيف Id كـ tie-breaker).
06

Mutations والـ errors

Mutations and error design
Practical

GraphQL بيرجع HTTP 200 حتى لو فيه errors (في errors array)، فالـ client ما يقدرش يعتمد على status codes. الممارسة المعتمدة: أخطاء البيزنس المتوقعة جزء من الـ schema (payload union أو errors field)، والـ exceptions غير المتوقعة بس في errors.

C#mutation conventions with typed errors
public sealed class Mutation
{
    [Authorize, Error<PlanLimitReachedException>, Error<NoSourcesException>]
    public async Task<AnswerResult> AskQuestionAsync(string question, [Service] IAskQuestion ask,
        [Service] ITenantContext t, ClaimsPrincipal user, CancellationToken ct)
    {
        var r = await ask.HandleAsync(new(t.TenantId, user.GetUserId(), question), ct);
        return r.Status switch
        {
            AnswerStatus.LimitReached => throw new PlanLimitReachedException(),
            AnswerStatus.NoSources => throw new NoSourcesException(),
            _ => r
        };
    }
}
// With mutation conventions enabled, the schema exposes: askQuestion(input) { answerResult { … } errors { ... on PlanLimitReachedError { message } } }

كده الـ Angular client بيعمل switch على نوع الخطأ (typed) ويعرض شاشة الـ upgrade، بدل ما يحلل نص رسالة.

07

الأمان: الـ query نفسها ممكن تبقى هجوم

Securing a GraphQL API
Deep dive
الخطرمثالالحماية
Deep/nested queriesdocuments { owner { documents { owner { … } } } } عمقه 20max depth، و cost analysis (Hot Chocolate بيحسب cost لكل field وبيرفض فوق الحد)
Batching abuse1000 operation في request واحد، أو aliases كتير لنفس الحقل (brute force على login)حد لعدد الـ operations والـ aliases، rate limit بالـ cost مش بعدد الـ requests
Introspection في الإنتاجخريطة كاملة للـ API للمهاجماقفلها أو قصرها على المستخدمين المصرح لهم في الإنتاج
Arbitrary queriesأي client يبعت أي شكلPersisted operations (trusted documents): السيرفر بيقبل بس queries متسجلة مسبقًا بـ hash من build الـ client
Authorization ناقصالـ root محمي، بس field متداخل بيكشف بيانات (document.owner.email)[Authorize] على الـ types/fields الحساسة + tenant filters في كل data access + اختبارات

الـ persisted operations هي أقوى حماية لـ API بيخدم تطبيقك انت بس (first-party): Angular build بيطلّع ملف بالـ operations، بيتسجل على السيرفر، والـ requests بتبعت الـ hash. كده أي query «مبتكرة» مرفوضة، والـ CDN caching ممكن على GET بالـ hash.

08

الـ schema evolution: deprecate مش version

Evolving the schema
Practical
  • Additive changes آمنة: حقل جديد nullable، type جديد، argument اختياري.
  • Breaking: حذف/إعادة تسمية حقل، تحويل nullable لـ non-null في input أو العكس في output، تغيير type.
  • الأسلوب: [GraphQLDeprecated("Use questionCount")]، راقب الـ usage (field-level telemetry)، واحذف لما الاستخدام يوصل صفر. الـ persisted operations بتخليك تعرف بالظبط مين بيستخدم إيه.
  • Schema checks في CI: صدّر الـ SDL وقارنه بالنسخة اللي في main (زي OpenAPI diff في OpenAPI).
09

GraphQL ولا REST ولا gRPC؟

Choosing an API style
Deep dive
المعيارRESTGraphQLgRPC
أنسب clientأي حد: شركاء، public API، webhooksUIs غنية (web/mobile) بشاشات كتير مختلفةservice-to-service داخلي
CachingHTTP caching طبيعي (ETag، CDN)أصعب؛ persisted GET أو client cache (Apollo/urql)مش HTTP caching
Over/under-fetchingشائعمحلولعقد ثابت
تحكم في التكلفةبسيط (endpoint = تكلفة معروفة)محتاج cost analysisبسيط
File upload، streamingطبيعيممكن بس مش أصليstreaming ممتاز
Tooling للفريقالكل يعرفهمنحنى تعلم + codegenproto + codegen

القاعدة العملية: REST افتراضيًا. GraphQL لما عندك frontends متعددة بتحتاج تركيبات مختلفة من بيانات مترابطة، وفريق مستعد يدفع تمن الـ server-side complexity (N+1، cost، caching). وشائع جدًا: REST للعالم الخارجي، GraphQL كـ BFF للـ frontend، و gRPC بين الخدمات. ولاحظ إن Hot Chocolate 16 ضاف adapters للـ MCP والـ OpenAPI على نفس الـ schema — نقطة مهمة لو هتعرض نفس الـ capabilities لـ AI agents.

10

الـ client من Angular

Consuming GraphQL from Angular
Practical
TypeScripttyped operation with a plain HttpClient (codegen produces the types)
// generated by GraphQL Code Generator from the schema + .graphql files
import { DashboardDocument, DashboardQuery, DashboardQueryVariables } from './generated/graphql';

@Injectable({ providedIn: 'root' })
export class GraphQLClient {
  private http = inject(HttpClient);
  query<T, V>(document: string, variables: V) {
    return this.http.post<{ data: T; errors?: { message: string }[] }>('/graphql', { query: document, variables }).pipe(
      map(r => { if (r.errors?.length) throw new Error(r.errors[0].message); return r.data; }));
  }
}

// component
dashboard = toSignal(inject(GraphQLClient).query<DashboardQuery, DashboardQueryVariables>(DashboardDocument, { first: 5 }));

لتطبيقات أكبر: Apollo Angular (normalized cache، optimistic updates) — بس ابدأ بسيط. والـ codegen في CI بيخلي أي breaking change في الـ schema يبان كـ compile error في الـ frontend.

11

اختبار GraphQL server

Testing the GraphQL API
Practical
C#schema snapshot + execution tests
public sealed class SchemaTests
{
    [Fact]
    public async Task Schema_has_not_changed_unexpectedly()
    {
        var executor = await new ServiceCollection()
            .AddGraphQLServer().AddQueryType<Query>().AddMutationType<Mutation>()
            .AddProjections().AddFiltering().AddSorting()
            .BuildRequestExecutorAsync();
        var sdl = executor.Schema.ToString();
        await Verify(sdl);                           // snapshot test (Verify/CookieCrumble): every schema diff shows up in the PR
    }
}

public sealed class DocumentQueryTests(GraphQLTestApp app) : IClassFixture<GraphQLTestApp>
{
    [Fact]
    public async Task Tenant_A_never_sees_tenant_B_documents()
    {
        var res = await app.ExecuteAsAsync(tenant: "A", """{ documents(first: 50) { nodes { id title } } }""");
        Assert.DoesNotContain(res.Nodes, d => app.SeededDocsOf("B").Contains(d.Id));
    }

    [Fact]
    public async Task Overly_deep_query_is_rejected()
    {
        var res = await app.ExecuteAsAsync(tenant: "A", DeepQueries.Depth(15));
        Assert.Contains(res.Errors, e => e.Code is "HC0047" or "COST_EXCEEDED");   // error codes vary by version: assert on your config
    }
}

تلات أنواع لازم يكونوا موجودين: snapshot للـ schema (كل تغيير مرئي)، اختبارات isolation والـ authorization على مستوى الحقول، واختبارات حماية (depth/cost/page size). والـ DataLoaders بتتختبر بعدد الـ queries (EF Core interceptor بيعد الأوامر) — query بـ 50 مستند لازم تعمل 2–3 SQL commands مش 51.

12

أخطاء شائعة

Common mistakes
Basics
  • Resolvers بتعمل query لكل parent (N+1) من غير DataLoader/batching.
  • مفيش depth/cost limits ولا max page size.
  • Authorization على الـ root بس، والحقول المتداخلة مكشوفة.
  • Introspection مفتوح في الإنتاج لـ API داخلي.
  • كشف الـ EF entities كـ GraphQL types مباشرة (كل عمود بقى API عام).
  • اختيار GraphQL لـ API بسيط CRUD لشركاء — REST أوضح وأسهل في الـ caching.
13

اختبر فهمك

Knowledge check
Basics

Query بتطلب 100 مستند ومع كل واحد owner. السيرفر بيعمل 101 query. الحل الصح في GraphQL؟

أقوى حماية لـ GraphQL API بيخدم تطبيق Angular بتاعك بس؟

14

تمارين محلولة

Worked exercises
Practical
1: صمّم schema لصفحة «مستنداتي» في الـ Capstone مع فلاتر وترتيب و pagination

الحل: documents(first, after, where: { status: { eq: READY }, title: { contains } }, order: [{ updatedAt: DESC }]) بـ connection، MaxPageSize 50، projection بس للحقول المطلوبة، questionCount عبر DataLoader بيعمل GROUP BY واحد للـ ids، tenant filter في الـ root + EF query filter، و [Authorize] على الـ type. والـ filtering fields محدودة صراحة (مش كل الأعمدة) عشان ما تفتحش queries بطيئة من غير index.

2: client بيبعت query بـ 300 alias لـ login mutation

الحل: ده brute force مستخبي في request واحد، فـ rate limit بعدد الـ requests ما بيكشفوش. الحماية: حد لعدد الـ aliases/root fields، cost analysis، rate limiting حسب الـ cost أو عدد الـ operations، و login أصلًا مكانه endpoint REST/OIDC مش GraphQL mutation.

15

أسئلة إنترفيو

Interview questions
Basics
(Junior) إيه الفرق بين GraphQL و REST؟
REST بيعرض resources ثابتة على URLs مختلفة؛ GraphQL بيعرض schema واحدة على endpoint واحد والـ client بيحدد شكل البيانات المطلوب بالظبط، فبيقلل over/under-fetching وعدد الـ round trips.
(Mid) إزاي بتحل N+1 في GraphQL؟
DataLoaders أو batch resolvers بيجمعوا المفاتيح في نفس دورة التنفيذ ويعملوا query واحدة، مع projections عشان SQL يجيب الأعمدة المطلوبة بس.
(Senior) إمتى ترفض GraphQL؟
لـ public/partner APIs بسيطة محتاجة HTTP caching ووضوح، أو فريق مش مستعد يدير الـ cost analysis والـ batching والـ security الخاصة بيه. GraphQL بيستاهل كـ BFF لـ UIs غنية متعددة.
↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

التوثيق الرسمي — Official documentation

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس