Zaraz 上下文丰富器(Context Enricher)是一种工具,可通过 Cloudflare Worker 修改或丰富在 Zaraz 中使用的 上下文。上下文丰富器允许您访问客户端和系统变量。
要使用上下文丰富器,您首先需要创建一个新的 Cloudflare Worker。您可以通过 Cloudflare 仪表板或使用 Wrangler 创建。
要在 Cloudflare 仪表板中创建新 Worker:
-
在 Cloudflare 仪表板中,前往 **Workers & Pages(Workers 和 Pages)**页面。
Go to Workers & Pages ↗ -
选择 Create application(创建应用程序)。
-
为您的 Worker 指定名称,然后选择 Deploy(部署)。
-
选择 Edit code(编辑代码)。
您现在已创建了一个会响应 “Hello world.” 的基本 Worker。要在将其用作上下文丰富器时使其可用,您需要更改代码以返回上下文:
export default {
async fetch(request, env, ctx) {
const { system, client } = await request.json();
// Here goes your modification to the system or client objects.
/*
For example, to change the country to a fictitious "Pirate's Island" ("PI"), use:
system.device.location.country = 'PI';
*/
return new Response(JSON.stringify({ system, client }));
},
};继续阅读以了解更完整的不同用例示例,或参阅 Zaraz Context。
现在您的 Worker 已发布,您可以在 Zaraz 设置中选择它:
-
在 Cloudflare 仪表板中,前往 **Settings(设置)**页面。
Go to Settings ↗ -
选择您的上下文丰富器 Worker。
-
保存设置。
您的上下文丰富器现在将在该给定 zone 中的所有 Zaraz 请求上运行。
您可以使用上下文丰富器向上下文添加信息。例如,您可以使用 API 获取用户所在位置的当前天气并将其添加到上下文中。
function getWeatherForLocation({ client, system }) {
// Get the location from the context.
const { city } = system.device.location;
// Get the weather from an API.
const response = await fetch(
`https://wttr.in/${encodeURIComponents(city)}?format=j1`
).then((response) => response.json());
// Add the weather to the context.
client.weather = weather;
return { client, system };
}
export default {
async fetch(request, env, ctx) {
const { system, client } = await request.json();
// Add the weather to the context.
const newContext = getWeatherForLocation({ system, client });
// Return as JSON
return new Response(JSON.stringify(newContext));
},
};现在,您可以在 Zaraz 中的任何位置使用 weather 属性,方法是从属性输入中选择 Track Property 并输入 weather。
假设我们要屏蔽敏感信息,例如电子邮件。为此,我们将替换上下文中所有出现的电子邮件地址。请注意,这仅是一个示例,可能不适用于所有边缘情况或用例。
为简化此示例,我们将替换所有包含 @ 符号的字符串:
function redactEmailAddressesFromObject(context) {
// Loop through all keys of the object.
for (const key in context) {
// Check if the value is a string.
if (typeof context[key] === "string") {
// Check if the string contains an @ symbol.
if (context[key].includes("@")) {
// Replace the string with a redacted version.
context[key] = "[email protected]";
}
} else if (typeof context[key] === "object") {
// Recursively call this function to redact the object.
context[key] = redactEmailAddressesFromObject(context[key]);
}
}
return context;
}
export default {
async fetch(request, env, ctx) {
const { system, client } = await request.json();
// Redact email addresses from the context.
const newContext = redactEmailAddressesFromObject({ system, client });
// Return as JSON
return new Response(JSON.stringify(newContext));
},
};