ข้ามไปยังเนื้อหา

การ Query Collection

endpoint แบบ collection อย่าง GET /articles อาจคืนค่ามาแค่สิบแถวหรือสิบล้านแถวก็ได้ การคืนทั้งหมดออกมาไม่เคยเป็นคำตอบที่ถูกต้อง ความสามารถในการ query สี่อย่างจะเปลี่ยน list ดิบ ๆ ให้กลายเป็นสิ่งที่ client ใช้งานได้อย่างมีประสิทธิภาพ

flowchart LR
  C[GET /articles] --> P[Pagination: how many, which slice]
  C --> F[Filtering: which rows]
  C --> S[Sorting: what order]
  C --> Fl[Field selection: which fields]
ทั้งสี่อย่างถูกระบุผ่าน query parameter บน collection

ทั้งสี่อย่างนี้อยู่ใน query string เพราะบอกว่า คุณอยากได้มุมมองแบบไหนของ collection ไม่ใช่ อยากได้ resource ตัวไหน ตัวตน (identity) อยู่ที่ path ส่วน query เป็นตัวกำหนดรูปร่างของผลลัพธ์

  • Pagination — offset เทียบกับ cursor และ response envelope
  • Filtering & sorting — การเลือกและจัดลำดับแถว
  • Field selection — sparse fieldsets และการ expand ความสัมพันธ์
  • Search & envelopes — full-text search และ wrapper ที่สม่ำเสมอ
parameter ของ pagination, filtering และ sorting ควรอยู่ที่ไหน?
การทำ GET แบบไม่ filter บน collection ขนาดใหญ่ ควรทำอะไรโดยปริยาย?