Creare un endpoint API con funzioni Edge
Una funzione Edge di AEM è un modulo JavaScript che viene eseguito su Adobe CDN (Fastly Compute). Puoi esporlo come uno o più endpoint HTTP associando le regole del selettore di origine CDN a un gestore eventi di recupero nel codice.
Questa pagina descrive il contratto e i file chiave. È possibile scrivere qualsiasi logica nel gestore, incluse le chiamate fetch() in uscita ad altri sistemi. Mantieni il gestore veloce e di breve durata in modo che si adatti al runtime edge.
Prerequisiti
- Un progetto AEM Edge Functions basato sul modello standard
- Adobe CLI con il plug-in AEM Edge Functions installato
Per la prima configurazione, vedere Configurazione su AEM as a Cloud Service o Configurazione su Edge Delivery Services.
Come una richiesta HTTP raggiunge il codice
Una richiesta raggiunge la funzione Edge di AEM in due passaggi: il selettore di origine CDN indirizza l’endpoint alla funzione, quindi viene eseguito il gestore eventi di recupero.
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 o kvs facoltativisrc/index.jsResponseIl selettore di origine e il nome della funzione devono essere allineati. Se edgeFunctions.yaml dichiara my-edge-function, il selettore di origine utilizza edgefunction-my-edge-function in cdn.yaml.
# 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
Ogni endpoint necessita della propria regola del selettore di origine in cdn.yaml. Una funzione Edge di AEM può servire più endpoint, ma la rete CDN deve inoltrare ciascun percorso a tale funzione. Impostare skipCache: false per consentire il caching CDN per risposte stabili oppure skipCache: true per ignorare la cache CDN per le risposte dinamiche o personalizzate.
Per le opzioni del selettore origine, vedi Selettori origine.
Gestire le richieste
Ogni funzione Edge di AEM registra un gestore di eventi di recupero. Adobe CDN richiama tale gestore per ogni richiesta corrispondente. Il gestore legge Request in ingresso, esegue la logica e restituisce 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();
}
}
Punti chiave:
addEventListener("fetch", ...) invia ogni richiesta al gestore eventi di recupero. Vedi FetchEvent.responseWithevent.request è un’API Fetch standard Request (metodo, URL, intestazioni, corpo). Vedere Riferimento richiestanew Response(body, { status, headers }) per controllare lo stato, il tipo di contenuto e le intestazioni della cache. Vedi Riferimento rispostaurl.pathname, metodo HTTP, intestazioni o parametri di query in handleRequestevent.client espone i dettagli di connessione come l’indirizzo IP del client. Vedere FetchEvent.clientLa corrispondenza dell’endpoint risiede in index.js. Con l’aumento degli endpoint, sposta la logica del gestore in file separati e importali, come my-api.js nell’esempio precedente. Consulta Distribuire più endpoint con le funzioni Edge per conoscere i pattern man mano che la superficie API si espande.
Scrivi la logica del gestore
All’interno di ciascun gestore endpoint, puoi eseguire qualsiasi JavaScript che si adatti al runtime edge. Mantieni il lavoro veloce e di breve durata. Preferisci trasformazioni leggere, ricerche geografiche, semplici risposte JSON o HTML e piccole aggregazioni rispetto a elaborazioni lunghe o complesse.
Una risposta minima si presenta così:
if (url.pathname === "/status" && req.method === "GET") {
return new Response("OK", { status: 200 });
}
Puoi restituire JSON, HTML o testo normale. Impostare le intestazioni su Response per controllare il tipo di contenuto e il caching:
return new Response(JSON.stringify({ status: "ok" }), {
status: 200,
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=300",
},
});
Quando hai bisogno di dati da un altro sistema, chiamalo con fetch(). Mantieni le credenziali nella funzione Edge di AEM. Non esporre segreti nel JavaScript client.
// 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 };
Le chiamate fetch() in uscita seguono in genere questo modello:
- Deriva contesto dalla richiesta (
headers,event.client, helper di geolocalizzazione Fastly). - Genera
Requestnell’altro sistema. - Chiamare
await fetch(request)(facoltativamente con un’origine denominatabackend). - Analizzare la risposta e restituire un nuovo
Responseal client.
Si applicano i limiti della piattaforma. Ogni chiamata supporta fino a 32 chiamate di recupero in uscita. Per informazioni sul comportamento della cache nelle chiamate di recupero, vedere Memorizzazione in cache nelle funzioni Edge di AEM.
Altri esempi di codice
Per esempi di lavoro completi, consulta la piattaforma di avvio delle funzioni Edge di AEM: