การใช้งาน Composable Directives
ทำให้ directive หนึ่งสามารถปรับเปลี่ยนพฤติกรรมของ directive อีกตัวได้
ฟังก์ชันนี้ช่วยให้สามารถใช้ directive ที่ปกติไม่สามารถใช้ได้เนื่องจากประเภทไม่ตรงกัน (กล่าวคือ เมื่อ directive ไม่สามารถนำไปใช้กับฟิลด์ได้ เพราะมี input ที่แตกต่างจาก output ของฟิลด์)
ตัวอย่างเช่น ฟิลด์ capabilities คืนค่า [String] (อาร์เรย์ของสตริง) แต่ directive @strUpperCase รับ String ดังนั้น การรันคิวรีต่อไปนี้จะเกิดข้อผิดพลาดเนื่องจากประเภทไม่ตรงกัน:
query {
user(by: {id: 1}) {
capabilities @strUpperCase
}
}ด้วย composable directives เราสามารถใช้ directive @underEachArrayItem (ซึ่งวนซ้ำผ่านอาร์เรย์ของ elements และนำ directive ที่ซ้อนอยู่ไปใช้กับแต่ละ element) เพื่อเตรียมพื้นฐานก่อนที่ @strUpperCase จะถูกรัน ทำให้มันรับ element เดียว (ประเภท String)
คิวรีข้างต้นสามารถทำได้ดังนี้:
query {
user(by: {id: 1}) {
capabilities
@underEachArrayItem
@strUpperCase
}
}Meta Directives
Meta directive แต่ละตัวสามารถส่งผลกระทบ (หรือ "ซ้อน") หลาย directives พร้อมกันได้ directives ใดที่ได้รับผลกระทบจะถูกระบุผ่านอาร์กิวเมนต์ affectDirectivesUnderPos ซึ่งรับอาร์เรย์ของจำนวนเต็มบวก โดยแต่ละตัวกำหนดตำแหน่งสัมพัทธ์ของ directive ที่ได้รับผลกระทบ
ตามค่าเริ่มต้น อาร์กิวเมนต์ affectDirectivesUnderPos มีค่าเริ่มต้นเป็น [1] ซึ่งหมายความว่าจะส่งผลกระทบต่อ directive ที่อยู่ถัดไปทันที
ในตัวอย่างด้านล่าง เรามี:
@underEachArrayItemคือ meta directive@strTranslateถูกซ้อนอยู่ใต้@underEachArrayItem(ค่าเริ่มต้นโดยปริยายaffectDirectivesUnderPos: [1])
{
someField
@underEachArrayItem
@strTranslate
}ในตัวอย่างด้านล่าง แทนที่จะเป็นเช่นนั้น เรามี:
@strTranslateและ@strUpperCaseถูกซ้อนอยู่ใต้@underEachArrayItem(ตามที่ระบุโดยตำแหน่งสัมพัทธ์[1, 2]ในอาร์กิวเมนต์affectDirectivesUnderPos)
{
someField
@underEachArrayItem(affectDirectivesUnderPos: [1, 2])
@strTranslate
@strUpperCase
}Meta directives ยังสามารถซ้อนอยู่ภายใน meta directives ได้
ในตัวอย่างด้านล่าง เรามี:
@underEachArrayItemคือ meta directive ระดับสูงสุด@underJSONObjectPropertyถูกซ้อนอยู่ใต้@underEachArrayItem@strUpperCaseถูกซ้อนอยู่ใต้@underJSONObjectProperty
query UppercaseEntriesInsideObject {
entries: _echo(value: [
{
text: "Hello my friends"
},
{
text: "How do you like this software so far?"
}
])
@underEachArrayItem
@underJSONObjectProperty(by: { key: "text" })
@strUpperCase
}การตั้งค่า
หากต้องการเปิดหรือปิด composable directives ใน GraphQL schema ให้ไปที่โมดูล "Composable Directives" ในหน้า Settings และทำเครื่องหมายหรือยกเลิกเครื่องหมายในช่องทำเครื่องหมาย Enable composable directives?:

หากต้องการเปิดหรือปิด composable directives บน endpoint เฉพาะ ให้เลือกตัวเลือกที่ต้องการในบล็อก "Composable Directives" จาก Schema Configuration ที่เกี่ยวข้อง:
