Thuta Learning
ရှာဖွေရန်
GraphQL
AdvancedWeb Developmentbeginner

Performance နှင့် Safety — Caching, Depth/Complexity Limits

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Performance နှင့် Safety — Caching, Depth/Complexity Limits concept ကို နားလည်ရှင်းပြနိုင်ရန်
  • နမူနာ GraphQL query/code ကို ကိုယ်တိုင် run ပြီး output စစ်နိုင်ရန်
  • Tutorial Platform project နှင့် production scenario တွင် မှန်ကန်စွာအသုံးချနိုင်ရန်

နားလည်ထားရမယ့် အချက်

GraphQL query တိုင်းက shape မတူတာကြောင့် REST လို URL-based HTTP caching ကို တိုက်ရိုက်အသုံးမပြုနိုင်ပါ—field-level `@cacheControl` directive/response caching plugin တွေကနေ per-field TTL သတ်မှတ်ရပါတယ်။ Client က deeply nested/recursive query (ဥပမာ `author { tutorials { author { tutorials { ... } } } }`) ပို့လို့ရနိုင်တာကြောင့် depth limit နှင့် complexity scoring rule (field cost weight) ကို server-level validation rule အဖြစ် ထည့်ရပါတယ်—resource exhaustion attack ကို ကာကွယ်ဖို့ပါ။ Persisted queries ကတော့ full query text အစား hash ID တစ်ခုပဲ network ပေါ်ပို့ခြင်းဖြင့် bandwidth/parsing cost လျှော့ပေးပါတယ်။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

Tutorial Platform ရဲ့ `tutorials` query field ကို `@cacheControl(maxAge: 60)` ဖြင့် mark လုပ်ပြီး public catalog data ကို 60 seconds cache လုပ်မယ်။ `depthLimit(6)` validation rule ဖြင့် recursive author↔tutorials query attack ကို block လုပ်ပြီး `createComplexityLimitRule(1000)` ဖြင့် field count weighted total ကို ကန့်သတ်ပါမယ်။

အတူတူ စမ်းရေးကြည့်မယ်

typescript
import depthLimit from 'graphql-depth-limit';
import { createComplexityLimitRule } from 'graphql-validation-complexity';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(6), createComplexityLimitRule(1000)],
});
You should see
Depth/complexity limiting rule ဖြစ်ဆောင်ရွက်ပြီး caching strategy တစ်ခုကို ရှင်းပြနိုင်မည်။

၅ မိနစ် စမ်းကြည့်

`tutorials` field ကို 3-level nested (`tutorials { comments { author { tutorials } } }`) query attack တစ်ခု ရေးပြီး `depthLimit` ဘယ်လို block လုပ်မလဲ ရှင်းပြပါ။

သတိလေးတစ်ချက်

Mutation field များကို `@cacheControl` ဖြင့် cache လုပ်မိရင် stale/incorrect write result ကို client ဆီ ပြန်ပေးနိုင်ပါတယ်—cache ကို read-only query fields အတွက်သာ သုံးပါ။

Apollo Server — CachingGraphQL

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Mutation field များကို `@cacheControl` ဖြင့် cache လုပ်မိရင် stale/incorrect write result ကို client ဆီ ပြန်ပေးနိုင်ပါတယ်—cache ကို read-only query fields အတွက်သာ သုံးပါ။
  • နမူနာ query/mutation ကို production API ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test server နှင့် recoverable data ပေါ်တွင် အရင်အတည်ပြုပါ။

လေ့ကျင့်ခန်း

`tutorials` field ကို 3-level nested (`tutorials { comments { author { tutorials } } }`) query attack တစ်ခု ရေးပြီး `depthLimit` ဘယ်လို block လုပ်မလဲ ရှင်းပြပါ။

You'll know it worked when: Depth/complexity limiting rule ဖြစ်ဆောင်ရွက်ပြီး caching strategy တစ်ခုကို ရှင်းပြနိုင်မည်။

Performance နှင့် Safety — Caching, Depth/Complexity Limits | Thuta Learning