使用Edge函式建立API端點
AEM Edge函式是在Adobe CDN (Fastly Compute)上執行的JavaScript模組。 您可以將CDN來源選擇器規則與程式碼中的擷取事件處理常式配對,以將其公開為一或多個 HTTP端點。
本頁涵蓋合約與重要檔案。 您可以在處理常式中寫入任何邏輯,包括對其他系統的輸出fetch()呼叫。 讓處理常式快速且短暫,以符合邊緣執行階段。
先決條件
- 以樣版範本為基礎的AEM Edge函式專案
- 已安裝Adobe Edge Functions外掛程式的AEM CLI
第一次設定時,請參閱在AEM as a Cloud Service上設定或在Edge Delivery Services上設定。
HTTP要求如何到達您的程式碼
要求會透過兩個步驟到達您的AEM Edge函式:CDN來源選擇器將端點路由至函式,然後您的擷取事件處理常式就會執行。
Browser → CDN origin selector (cdn.yaml) → AEM Edge Function (index.js) → Your handler logic (optional fetch to other systems)
config/cdn.yamlconfig/edgeFunctions.yamlconfigs、secrets或kvssrc/index.jsResponse原始選取器與函式名稱必須對齊。 如果edgeFunctions.yaml宣告my-edge-function,則來源選擇器會在cdn.yaml中使用edgefunction-my-edge-function。
# config/edgeFunctions.yaml
kind: "EdgeFunctions"
version: "1"
data:
functions:
- name: my-edge-function #<name-of-the-function>
# config/cdn.yaml (origin selector excerpt)
kind: 'CDN'
version: '1'
data:
originSelectors:
rules:
- name: route-status-endpoint-to-edge-function # logical name for the origin selector rule
when: { reqProperty: path, equals: "/status" } # path to match
action:
type: selectAemOrigin
originName: edgefunction-my-edge-function # edgefunction-<name-of-the-function>
skipCache: false # false to use the CDN cache for this path
- name: route-my-api-to-edge-function # logical name for the origin selector rule
when: { reqProperty: path, equals: "/my-api" } # path to match
action:
type: selectAemOrigin
originName: edgefunction-my-edge-function # edgefunction-<name-of-the-function>
skipCache: true # true to bypass the CDN cache for this path
每個端點在cdn.yaml中都需要各自的原始選擇器規則。 一個AEM Edge函式可為多個端點提供服務,但CDN必須將每個路徑轉送至該函式。 設定skipCache: false允許CDN快取以取得穩定的回應,或設定skipCache: true略過CDN快取以取得動態或個人化的回應。
如需來源選取器選項,請參閱來源選取器。
處理請求
每個AEM Edge函式都會註冊擷取事件處理常式。 Adobe CDN會針對每個相符請求叫用該處理常式。 處理常式會讀取傳入的Request、執行您的邏輯,並傳回Response。
// src/index.js
import { myApiHandler } from "./my-api.js";
import * as response from "./lib/response.js";
// entry point for the AEM Edge Function
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
async function handleRequest(event) {
// event.request is a standard Fetch API Request (method, URL, headers, body)
const req = event.request;
const url = new URL(req.url);
try {
// endpoint matching
if (url.pathname === "/status" && req.method === "GET") {
return new Response("OK", { status: 200 });
} else if (url.pathname === "/my-api" && req.method === "GET") {
return await myApiHandler(req, event.client);
}
// add more endpoints here
return response.notFound();
} catch (err) {
console.log(err);
return response.error();
}
}
要點:
addEventListener("fetch", ...)將每個要求都連線到您的擷取事件處理常式,請參閱FetchEvent.responseWithnew Response(body, { status, headers })以控制狀態、內容型別和快取標頭,請參閱回應參考url.pathname、HTTP方法、標頭或handleRequest內的查詢引數event.client公開連線詳細資料,例如使用者端IP位址,請參閱FetchEvent.client端點符合存留在index.js中。 隨著您的端點成長,請將處理常式邏輯移動至個別檔案並匯入,如上述範例中的my-api.js所做。 當您的API表面展開時,請參閱使用Edge函式提供多個端點以取得模式。
撰寫您的處理常式邏輯
在每個端點處理常式中,您可以執行任何適合邊緣執行階段的JavaScript。 讓工作快速且短暫。 比起長時間執行或繁重的運算,偏好輕量型的轉換、地理查閱、簡單的JSON或HTML回應以及小型彙總。
最低回應如下所示:
if (url.pathname === "/status" && req.method === "GET") {
return new Response("OK", { status: 200 });
}
您可以傳回JSON、HTML或純文字。 在Response上設定標頭以控制內容型別和快取:
return new Response(JSON.stringify({ status: "ok" }), {
status: 200,
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=300",
},
});
當您需要其他系統的資料時,請使用fetch()呼叫它。 在AEM Edge函式中保留認證。 請勿在使用者端JavaScript中公開秘密。
// src/my-api.js
async function myApiHandler(req, client) {
const backendRequest = new Request("https://api.example.com/data");
// optionally, you can add headers to the request
// backendRequest.headers.set("Authorization", `Bearer <your-access-token>`);
const backendResponse = await fetch(backendRequest);
if (!backendResponse.ok) {
return new Response("Backend error", { status: 502 });
}
const data = await backendResponse.json();
return new Response(JSON.stringify(data), {
status: 200,
headers: {
"Content-Type": "application/json",
"Cache-Control": "max-age=300",
},
});
}
export { myApiHandler };
傳出fetch()呼叫通常遵循此模式:
- 從要求衍生內容(
headers、event.client、Fastly地理位置協助程式)。 - 將
Request建置到其他系統。 - 呼叫
await fetch(request)(可選擇使用名稱為backend的來源)。 - 剖析回應並將新的
Response傳回給使用者端。
適用平台限制。 每個引動最多可支援32個傳出擷取呼叫。 如需擷取呼叫的快取行為,請參閱在AEM Edge函式中快取。