AEM Headless SDK

AEM Headless SDK是一组库,客户可以使用这些库通过HTTP快速轻松地与AEM Headless API交互。

AEM Headless SDK可用于各种平台:

持久 GraphQL 查询

使用GraphQL使用持久查询查询查询AEM(而不是 客户端定义的GraphQL查询)允许开发人员在AEM中保留查询(但不保留其结果),然后按名称请求执行查询。 持久化查询与SQL数据库中存储过程的概念类似。

持久化查询比客户端定义的GraphQL查询更具性能,因为持久化查询使用HTTPGET执行,HTTP数据可在CDN和AEM Dispatcher层中缓存。 持久化查询也有效,可定义API,并让开发人员不再需要了解每个内容片段模型的详细信息。

代码示例

以下是如何针对AEM执行GraphQL持久查询的代码示例。

 JavaScript示例

安装 @adobe/aem-headless-client-js 运行 npm install 命令。

$ npm i @adobe/aem-headless-client-js

此代码示例显示如何使用 @adobe/aem-headless-client-js npm模块使用 async/await 语法。 适用于JavaScript的AEM Headless SDK还支持 Promise语法.

此代码假定具有名称的持久查询 wknd/adventureNames 已在AEM作者上创建并发布到AEM发布。

import AEMHeadless from '@adobe/aem-headless-client-js';

// Initialize the AEMHeadless client with connection details
const aemHeadlessClient = new AEMHeadless({
    serviceURL: 'https://publish-p123-e789.adobeaemcloud.com',  // The AEM environment to query, this can be pulled out to env variables
    endpoint: '/content/cq:graphql/wknd-shared/endpoint.json',  // The AEM GraphQL endpoint, this is not used when invoking persisted queries.
})

/**
 * Uses the AEM Headless SDK to execute a persisted query with optional query variables.

 * @param {String} persistedQueryName the fully qualified name of the persisted query
 * @param {*} queryParameters an optional JavaScript object containing query parameters
 * @returns the GraphQL data or an error message
 */
export async function executePersistedQuery(persistedQueryName, queryParameters) {
    let data;
    let errors;

    try {
        // AEM GraphQL queries are asynchronous, either await their return or use Promise-based .then(..) { ... } syntax
        const response = await aemHeadlessClient.runPersistedQuery(persistedQueryName, queryParameters);
        // The GraphQL data is stored on the response's data field
        data = response.data;
    } catch (e) {
        console.error(e.toJSON())
        errors = e;
    }

    return { data, errors };
};

// Execute the persisted query using its name 'wknd-shared/adventures-by-slug' and optional query variables
let { data, errors } = executePersistedQuery('wknd-shared/adventures-by-slug', { "slug": "bali-surf-camp" });
 React useEffect(..) 示例

安装 @adobe/aem-headless-client-js 运行 npm install 命令。

$ npm i @adobe/aem-headless-client-js

此代码示例显示如何使用 React useEffect(…) 钩钩 执行对AEM GraphQL的异步调用。

使用 useEffect 在React中进行异步GraphQL调用非常有用,因为:

  1. 它为对AEM的异步调用提供同步包装器。
  2. 它减少了不必要的AEM请求。

此代码假定具有名称的持久查询 wknd-shared/adventure-by-slug 已在AEM作者上创建,并使用GraphiQL发布到AEM发布。

import AEMHeadless from '@adobe/aem-headless-client-js';
import { useEffect, useState } from "react";

// Initialize the AEMHeadless client with connection details
const aemHeadlessClient = new AEMHeadless({
    serviceURL: 'https://publish-p123-e789.adobeaemcloud.com', // The AEM environment to query
    endpoint: '/content/cq:graphql/wknd-shared/endpoint.json'         // The AEM GraphQL endpoint, this is not used when invoking persisted queries.
})

/**
 * Private, shared function that invokes the AEM Headless client.
 * React components/views will invoke GraphQL via the custom React useEffect hooks defined below.
 *
 * @param {String} persistedQueryName the fully qualified name of the persisted query
 * @param {*} queryParameters an optional JavaScript object containing query parameters
 * @returns the GraphQL data or an error message
 */
async function fetchPersistedQuery(persistedQueryName, queryParameters) {
  let data;
  let err;

  try {
    // AEM GraphQL queries are asynchronous, either await their return or use Promise-based .then(..) { ... } syntax
    const response = await aemHeadlessClient.runPersistedQuery(
      persistedQueryName,
      queryParameters
    );
    // The GraphQL data is stored on the response's data field
    data = response?.data;
  } catch (e) {
    // An error occurred, return the error messages
    err = e
      .toJSON()
      ?.map((error) => error.message)
      ?.join(", ");
    console.error(e.toJSON());
  }

  return { data, err };
}

/**
 * Calls the 'wknd-shared/adventure-by-slug' and provided the {slug} as the persisted query's `slug` parameter.
 *
 * @param {String!} slug the unique slug used to specify the adventure to return
 * @returns a JSON object representing the adventure
 */
export function useAdventureBySlug(slug) {
  const [adventure, setAdventure] = useState(null);
  const [errors, setErrors] = useState(null);

  useEffect(() => {
    async function fetchData() {
      // The key is the variable name as defined in the persisted query, and may not match the model's field name
      const queryParameters = { slug: slug };

      // Invoke the persisted query, and pass in the queryParameters object as the 2nd parameter
      const { data, err } = await fetchPersistedQuery(
        "wknd-shared/adventure-by-slug",
        queryParameters
      );

      if (err) {
        // Capture errors from the HTTP request
        setErrors(err);
      } else if (data?.adventureList?.items?.length === 1) {
        // Set the adventure data after data validation (there should only be 1 matching adventure)
        setAdventure(data.adventureList.items[0]);
      } else {
        // Set an error if no adventure could be found
        setErrors(`Cannot find adventure with slug: ${slug}`);
      }
    }
    fetchData();
  }, [slug]);

  return { adventure, errors };
}

调用自定义React useEffect 从React组件中的其他位置挂接。

import useAdventureBySlug from '...';

let { data, errors } = useAdventureBySlug('bali-surf-camp');

新建 useEffect 可以为React应用程序使用的每个持久查询创建挂钩。

 

GraphQL查询

AEM支持客户端定义的GraphQL查询,但最佳做法是使用AEM 持久GraphQL查询.

在此页面上