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

Unions နှင့် Fragments

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

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

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

`union` က interface နဲ့ဆင်တူပေမယ့် member types များအချင်းချင်း ဘုံ field မလိုအပ်ပါ—search result လို field type မတူသော object များ ပြန်ရနိုင်တဲ့ query အတွက် သင့်ပါတယ်။ Union member ကို query ရေးရာမှာ `... on Tutorial` လို inline fragment ဖြင့် type-specific fields တောင်းရပါတယ်။ Named fragment (`fragment TutorialCard on Tutorial { ... }`) ကတော့ field selection တစ်ခုကို query အများအတွင်း reuse လုပ်နိုင်အောင် ဖြစ်ပါတယ်။

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

Site-wide search feature ကို `union SearchResult = Tutorial | Author` ဖြင့် model လုပ်မယ်။ `TutorialCard` fragment ကို card component field list တစ်ခုတည်းအဖြစ်ရေးပြီး homepage query နဲ့ search query နှစ်ခုစလုံးမှာ reuse လုပ်ပါမယ်—field list ပြောင်းရင် နေရာတစ်ခုတည်းပြင်ရုံနဲ့ ပြီးပါမယ်။

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

graphql
union SearchResult = Tutorial | Author

fragment TutorialCard on Tutorial {
  id
  title
  difficulty
}

query Search($term: String!) {
  search(term: $term) {
    ... on Tutorial {
      ...TutorialCard
    }
    ... on Author {
      id
      name
    }
  }
}
You should see
Union type ကို query ရေးနိုင်ပြီး fragment ဖြင့် field selection ကို reuse လုပ်နိုင်မည်။

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

`union NotificationTarget = Tutorial | Comment` ရေးပြီး inline fragment နှစ်ခုနဲ့ query တစ်ခုရေးပါ။

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

Union query ရေးရာမှာ inline fragment မထည့်ဘဲ scalar field တိုက်ရိုက်ရွေးမိရင် validation error ဖြစ်ပါတယ်—union member types ဘုံ field guarantee မရှိလို့ပါ။

GraphQL — Queries and Mutations (Fragments)GraphQL

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

  • Union query ရေးရာမှာ inline fragment မထည့်ဘဲ scalar field တိုက်ရိုက်ရွေးမိရင် validation error ဖြစ်ပါတယ်—union member types ဘုံ field guarantee မရှိလို့ပါ။
  • နမူနာ query/mutation ကို production API ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test server နှင့် recoverable data ပေါ်တွင် အရင်အတည်ပြုပါ။

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

`union NotificationTarget = Tutorial | Comment` ရေးပြီး inline fragment နှစ်ခုနဲ့ query တစ်ခုရေးပါ။

You'll know it worked when: Union type ကို query ရေးနိုင်ပြီး fragment ဖြင့် field selection ကို reuse လုပ်နိုင်မည်။

Unions နှင့် Fragments | Thuta Learning