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

Object Types နှင့် Relationships

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

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

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

GraphQL object type တစ်ခုရဲ့ field က scalar အပြင် အခြား object type တစ်ခုလည်း ဖြစ်နိုင်ပါတယ်—ဒါက relational database ထဲက foreign key relationship ကို schema level မှာ ပုံဖော်ပေးတာပါ။ Query execute တဲ့အခါ field တစ်ခုချင်းစီအတွက် resolver function တစ်ခုစီ ခွဲခေါ်ပါတယ်—`Tutorial.author` field ကို resolve ရင် parent argument ထဲက tutorial object ကနေ `authorId` ယူပြီး author data ကို ဖတ်ပါတယ်။

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

`Author` type ကို `id`, `name`, `tutorials: [Tutorial!]!` ဖြင့် ကြေညာပြီး `Tutorial` type ထဲမှာ `author: Author!` field ထည့်မယ်။ Query တစ်ခုတည်းနဲ့ tutorial detail page က tutorial fields နဲ့ author name ကို round trip တစ်ခါတည်းနဲ့ ရနိုင်တော့ပါတယ်—REST version က endpoint နှစ်ခုလိုခဲ့တာနဲ့ ကွာခြားပါတယ်။

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

graphql
type Author {
  id: ID!
  name: String!
  tutorials: [Tutorial!]!
}

type Tutorial {
  id: ID!
  title: String!
  author: Author!
}

type Query {
  tutorial(id: ID!): Tutorial
}
You should see
Nested object types ရေးပြီး relationship field တစ်ခုကို schema ထဲ model လုပ်နိုင်မည်။

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

`Comment` type (`id`, `body`, `author: Author!`) တစ်ခု ထည့်ပြီး `Tutorial` type ထဲ `comments: [Comment!]!` field ဖြည့်ပါ။

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

Relationship field (`author`) ကို non-null (`Author!`) လုပ်ထားပေမယ့် data ထဲမှာ orphaned tutorial (author မရှိတော့) ရှိနေရင် resolver က crash ဖြစ်နိုင်ပါတယ်—data integrity ကို schema constraint နဲ့ တွဲစဉ်းစားပါ။

GraphQL — Schemas and TypesGraphQL

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

  • Relationship field (`author`) ကို non-null (`Author!`) လုပ်ထားပေမယ့် data ထဲမှာ orphaned tutorial (author မရှိတော့) ရှိနေရင် resolver က crash ဖြစ်နိုင်ပါတယ်—data integrity ကို schema constraint နဲ့ တွဲစဉ်းစားပါ။
  • နမူနာ query/mutation ကို production API ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test server နှင့် recoverable data ပေါ်တွင် အရင်အတည်ပြုပါ။

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

`Comment` type (`id`, `body`, `author: Author!`) တစ်ခု ထည့်ပြီး `Tutorial` type ထဲ `comments: [Comment!]!` field ဖြည့်ပါ။

You'll know it worked when: Nested object types ရေးပြီး relationship field တစ်ခုကို schema ထဲ model လုပ်နိုင်မည်။