|
| 1 | +import type { GoogleProvider } from "../../types/providers"; |
| 2 | +import type { GlobalChartOptions } from ".."; |
| 3 | +import type { ChartData } from "../../types/data"; |
| 4 | +import { |
| 5 | + getMetrics, |
| 6 | + getDateRange, |
| 7 | + DateFormat, |
| 8 | + GoogleDateFormat, |
| 9 | +} from "./utilities"; |
| 10 | +import client from "./client"; |
| 11 | +import type { protos } from "@google-analytics/data"; |
| 12 | +import type { Timeframes } from "../../types/widgets"; |
| 13 | +import { eachDayOfInterval, parse, isEqual, format } from "date-fns"; |
| 14 | + |
| 15 | +async function getGlobalChartData( |
| 16 | + provider: GoogleProvider, |
| 17 | + options: GlobalChartOptions |
| 18 | +) { |
| 19 | + const googleClient = client(provider); |
| 20 | + |
| 21 | + const { metrics } = options; |
| 22 | + const timeframe: Timeframes = (options.timeframe as Timeframes) ?? "30d"; |
| 23 | + |
| 24 | + const usedMetrics = getMetrics(metrics); |
| 25 | + |
| 26 | + const dateRange = getDateRange(timeframe); |
| 27 | + |
| 28 | + const dates = eachDayOfInterval({ |
| 29 | + start: dateRange.dates.startDate, |
| 30 | + end: dateRange.dates.endDate, |
| 31 | + }); |
| 32 | + |
| 33 | + const request: protos.google.analytics.data.v1beta.IRunReportRequest = { |
| 34 | + property: `properties/${provider.propertyId}`, |
| 35 | + dateRanges: [dateRange.formatted], |
| 36 | + dimensions: [{ name: "date" }], |
| 37 | + metrics: usedMetrics.map((metric) => { |
| 38 | + return { |
| 39 | + name: metric, |
| 40 | + }; |
| 41 | + }), |
| 42 | + keepEmptyRows: false, |
| 43 | + metricAggregations: [], |
| 44 | + }; |
| 45 | + |
| 46 | + const data = await googleClient.run.runReport(request).then((data) => data); |
| 47 | + |
| 48 | + const processedData: ChartData = usedMetrics.map((metric, index) => { |
| 49 | + return { |
| 50 | + label: metrics[index], |
| 51 | + data: dates.map((date, dateIndex) => { |
| 52 | + const matchingRow = data[0].rows?.find((row) => { |
| 53 | + if (row.dimensionValues?.[0].value) { |
| 54 | + const parsedDate = parse( |
| 55 | + row.dimensionValues[0].value, |
| 56 | + GoogleDateFormat, |
| 57 | + new Date() |
| 58 | + ); |
| 59 | + |
| 60 | + return isEqual(date, parsedDate); |
| 61 | + } |
| 62 | + |
| 63 | + return false; |
| 64 | + }); |
| 65 | + |
| 66 | + if (matchingRow) { |
| 67 | + const value = matchingRow.metricValues?.[index]?.value; |
| 68 | + |
| 69 | + return { |
| 70 | + timestamp: format(date, DateFormat), |
| 71 | + value: value ? parseInt(value) : 0, |
| 72 | + }; |
| 73 | + } else { |
| 74 | + return { |
| 75 | + timestamp: format(date, DateFormat), |
| 76 | + value: 0, |
| 77 | + }; |
| 78 | + } |
| 79 | + }), |
| 80 | + }; |
| 81 | + }); |
| 82 | + |
| 83 | + return processedData; |
| 84 | +} |
| 85 | + |
| 86 | +export default getGlobalChartData; |
0 commit comments