import {
getPropertyId,
formatPropertyPath,
executeRealtimeReport,
} from "../../client.js";
import type {
RunRealtimeReportInput,
RealtimeReportOutput,
ReportRow,
} from "../../types.js";
/**
* GA4 リアルタイムレポートを実行
*/
export async function runRealtimeReport(
input: RunRealtimeReportInput
): Promise<RealtimeReportOutput> {
const propertyId = getPropertyId(input.propertyId);
const property = formatPropertyPath(propertyId);
// デフォルト値の設定
const dimensions = input.dimensions || ["country", "deviceCategory"];
const metrics = input.metrics || ["activeUsers"];
// レポート実行
const response = await executeRealtimeReport({
property,
dimensions: dimensions.map((name) => ({ name })),
metrics: metrics.map((name) => ({ name })),
});
// 結果を整形
const rows: ReportRow[] = [];
const dimensionHeaders = response.dimensionHeaders || [];
const metricHeaders = response.metricHeaders || [];
for (const row of response.rows || []) {
const dimensionValues: Record<string, string> = {};
const metricValues: Record<string, number | string> = {};
// ディメンション値を取得
(row.dimensionValues || []).forEach((value, index) => {
const header = dimensionHeaders[index];
if (header?.name) {
dimensionValues[header.name] = value.value || "";
}
});
// メトリクス値を取得
(row.metricValues || []).forEach((value, index) => {
const header = metricHeaders[index];
if (header?.name) {
const rawValue = value.value || "0";
const numValue = parseFloat(rawValue);
metricValues[header.name] = isNaN(numValue) ? rawValue : numValue;
}
});
rows.push({ dimensions: dimensionValues, metrics: metricValues });
}
// 合計値の取得
let totals: Record<string, number | string> | undefined;
if (response.totals && response.totals.length > 0) {
totals = {};
const totalRow = response.totals[0];
(totalRow.metricValues || []).forEach((value, index) => {
const header = metricHeaders[index];
if (header?.name) {
const rawValue = value.value || "0";
const numValue = parseFloat(rawValue);
totals![header.name] = isNaN(numValue) ? rawValue : numValue;
}
});
}
return {
rows,
rowCount: rows.length,
totals,
};
}