เราสามารถใช้ fragment ในการแยกโค้ดที่ซ้ำกัน ออกมาไว้ที่เดียวได้ แบบนี้ครับ
fragment Blog on BlogType { id title subTitle content previewImage category wordCount recommend readingTime likeCount viewCount updatedAt createdAt author }
จากตัวอย่างข้างต้น เราสร้าง fragment ชื่อ Blog เพื่อเอาไปใช้ซ้ำกับหลาย ๆ จุดได้ โดยกำกับไว้ว่าเราสามารถใช้ได้กับ type ที่ชื่อว่า BlogType
แล้ว BlogType มาจากไหน ? ก็มาจาก Object Type ที่เราสร้างเอาไว้ เช่น บนเซิร์ฟเวอร์นั่นเอง
type BlogType { id title subTitle content previewImage category wordCount recommend readingTime likeCount viewCount updatedAt createdAt author }
ตอนใช้งานก็จัดการ spread เจ้า fragment เข้าได้ไปเลย ลองดูโค้ดเต็ม ๆ ด้านล่างเลยครับ
query fetchBlogs { topBlogs: blogs(sortBy: "likeCount") { ...Blog } recommendedBlogs: blogs(recommend: true) { ...Blog } shortBlogs: blogs(maxWord: 100) { ...Blog } }
fragment Blog on BlogType {
id
title
subTitle
content
previewImage
category
wordCount
recommend
readingTime
likeCount
viewCount
updatedAt
createdAt
author
}