Zaraz の Context Enricher は、Cloudflare Worker を使って Zaraz 全体で使われる コンテキスト を変更・補完する機能です。Context Enricher から、client 変数と system 変数にアクセスできます。
Context Enricher を使うには、先に新しい Cloudflare Worker を作成します。Cloudflare ダッシュボード、または Wrangler で作成できます。
Cloudflare ダッシュボードで新しい Worker を作成するには、次の手順を行います。
-
Cloudflare ダッシュボードで Workers & Pages ページを開きます。
Workers & Pages を開く ↗ -
Create application を選びます。
-
Worker に名前を付け、Deploy を選びます。
-
Edit code を選びます。
これで、"Hello world." を返す基本的な Worker ができました。Context Enricher として使うには、コンテキストを返すようにコードを変更します。
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 コンテキスト を参照してください。
Worker を公開したら、Zaraz の設定で選びます。
-
Cloudflare ダッシュボードで Settings ページを開きます。
Settings を開く ↗ -
Context Enricher 用の Worker を選びます。
-
設定を保存します。
以降、そのゾーンのすべての Zaraz リクエストで Context Enricher が実行されます。
Context Enricher で、コンテキストに情報を追加できます。たとえば、ユーザーの所在地の天気を 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));
},
};これで、属性入力から Track Property を選び、weather と入力すれば、Zaraz の任意の場所で 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));
},
};