การเขียนโค้ดด้วย API
การเขียนโค้ดด้วย APIการส่งข้อมูลไปยังบล็อกในตัวแก้ไข

การส่งข้อมูลไปยังบล็อกในตัวแก้ไข

เนื้อหาในตัวแก้ไข WordPress สร้างขึ้นผ่านบล็อก (Gutenberg) ที่ดึงข้อมูลจากเซิร์ฟเวอร์ผ่าน API WordPress core ใช้ WP REST API แต่เราสามารถใช้ Gato GraphQL เพื่อขับเคลื่อนบล็อกของเราเองได้เช่นกัน

มาสำรวจวิธีที่บล็อกสามารถดึงข้อมูลจาก GraphQL เซิร์ฟเวอร์กัน

Endpoint

เนื่องจากบล็อกถูกใช้งานภายในบริบทของตัวแก้ไข WordPress ผู้ใช้จึงล็อกอินอยู่แล้ว ดังนั้นเราสามารถเชื่อมต่อกับ GraphQL endpoint ภายใน (เข้าถึงได้เฉพาะใน wp-admin) แทนที่จะใช้ public endpoint

blockEditor endpoint ภายในนี้เข้าถึงได้ที่:

https://mysite.com/wp-admin/edit.php?page=gatographql&action=run_query&endpoint_group=blockEditor

endpoint นี้มีการกำหนดค่าล่วงหน้า (กล่าวคือ จะไม่นำการตั้งค่าของผู้ใช้จากปลั๊กอินมาใช้) จึงทำให้การทำงานมีความสอดคล้องกัน

นอกจากนี้ เราสามารถอ้างอิง JavaScript global variable GATOGRAPHQL_BLOCK_EDITOR_ADMIN_ENDPOINT ซึ่งมี URL ของ endpoint อยู่ได้อย่างสะดวก

คุณยังสามารถสร้าง internal endpoint ของคุณเอง และกำหนดค่าเฉพาะที่บล็อกของคุณต้องการล่วงหน้าได้ (เช่น เปิดใช้งาน nested mutations, เปิดใช้ namespacing, กำหนด CPT ที่สามารถ query ได้ หรือสิ่งอื่นๆ ที่มีใน Schema Configuration)

อีกทางเลือกหนึ่ง คุณสามารถสร้าง Persisted Queries และดึงข้อมูลจาก Persisted Queries แทน endpoint ดูวิธีที่โค้ด client ต้องปรับให้เข้ากัน

การเชื่อมต่อผ่าน fetch

เราสามารถใช้fetch method มาตรฐานในการเชื่อมต่อกับเซิร์ฟเวอร์

โค้ด JavaScript ต่อไปนี้ส่ง query พร้อมตัวแปรไปยัง GraphQL เซิร์ฟเวอร์ และแสดงผลลัพธ์ใน console

(async function () {
  const limit = 3;
  const data = {
    query: `
      query GetPostsWithAuthor($limit: Int) {
        posts(pagination: { limit: $limit }) {
          id
          title
          author {
            id
            name
          }
        }
      }
    `,
    variables: {
      limit: `${ limit }`
    },
  };
 
  const response = await fetch(
    GATOGRAPHQL_BLOCK_EDITOR_ADMIN_ENDPOINT,
    {
      method: 'post',
      body: JSON.stringify(data),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Content-Length': data.length,
      },
      credentials: 'include',
    }
  );
 
  /**
   * Execute the query, and await the response
   */
  const json = await response.json();
 
  /**
   * Check if the query produced errors, otherwise use the results
   */
  if (json.errors) {
    console.log(JSON.stringify(json.errors));
  } else {
    console.log(JSON.stringify(json.data));
  }
})();

การส่ง REST nonce header

หากต้องการดำเนินการที่รวม REST nonce ไว้ด้วย ให้เพิ่ม X-WP-Nonce header

พิมพ์ JS variable ที่มี nonce ผ่านโค้ด PHP:

// Generate HTML in the editor:
// <script type="text/javascript">var WP_REST_NONCE = "{ Nonce value }"</script>
add_action(
  'admin_print_scripts',
  function(): void {
    printf(
      '<script type="text/javascript">var %s = "%s"</script>',
      'WP_REST_NONCE',
      wp_create_nonce('wp_rest')
    );
  }
);

จากนั้นใส่ค่า nonce ในส่วน headers ของ fetch:

// ...
  headers: {
    'X-WP-Nonce': `${ WP_REST_NONCE }`,
    // ...
  };

การเชื่อมต่อผ่าน GraphQL client library

คุณยังสามารถใช้ GraphQL client library ที่ต้องการในการเชื่อมต่อกับเซิร์ฟเวอร์ได้ ตัวเลือกบางส่วนได้แก่:

นี่คือตัวอย่างที่ใช้ GraphQL request:

/* eslint-disable */
 
const { request, gql } = require(`graphql-request`)
 
main()
 
async function main() {
  const query = gql`
    query {
      posts {
        id
        title
        author {
          id
          name
        }
      }
    }
  `
 
  const data = await request(GATOGRAPHQL_BLOCK_EDITOR_ADMIN_ENDPOINT, query)
  console.log(data)
}

ปลั๊กอิน Gato GraphQL เองก็ขับเคลื่อนบล็อกผ่าน GraphQL โดยใช้ไลบรารี graphql-request

ดูซอร์สโค้ดของบล็อก "Schema Configuration" และdata store ของมัน