Last update:2024-09-03 17:00:37
This example demonstrates how to implement Edge Rendering using Edge Cloud Apps Function, with a network peering analysis as practical use case. Users simply provide an ASN (Autonomous System Number), and the function queries the PeeringDB API to calculate the shared facilities and exchange points between the user-provided ASN and a pre-configured target ASN (e.g., Apple’s). This information is dynamically inserted into a pre-existing HTML template using the HTMLRewriter
. The result is a customized, pre-rendered response delivered directly to the user.
Benefits of Edge Rendering
import { NetworkComparisonHandler, ErrorConditionHandler, AsnHandler } from "./peering-handlers";
import { Network } from "./peering-models-net";
import { apple } from './peering-utils-constants';
async function handleRequest(request) {
const url = new URL(request.url);
const asn = url.searchParams.get('asn'); // Fetch the user-provided ASN
console.log(`asn:${asn}`);
try {
if (asn) {
// Retrieve network information for Apple's ASN and the user-provided ASN
const apNetwork = await new Network(apple['asn']).populate();
const otherNetwork = await new Network(asn).populate();
// Calculate shared facilities and exchange points between the two networks
const sharedItems = await apNetwork.compare(otherNetwork);
console.log(`sharedItems: ${sharedItems.length}`);
let response = await fetch(request.url);
// Utilize HTMLRewriter to dynamically modify HTML content
return await new HTMLRewriter()
.on('#asnField', new AsnHandler(asn)) // Handle the ASN input field
.on('#formContainer', new NetworkComparisonHandler({apNetwork, otherNetwork, sharedItems})) // Handle the results display area
.transform(response);
} else {
return fetch(request.url);
}
} catch (e) {
console.error(`error:${e}`);
let response = await fetch(request.url);
return await new HTMLRewriter()
.on('#asnField', new AsnHandler(asn))
.on('#formContainer', new ErrorConditionHandler(asn))
.transform(response);
}
}
addEventListener("fetch", event => {
return event.respondWith(handleRequest(event.request));
});