-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (70 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use strict";
const { google } = require("googleapis");
exports.__esModule = true;
exports.getReport = getReport;
exports.executeAnalytics = executeAnalytics;
const scopes = [
// View and manage your Google Analytics data
"https://www.googleapis.com/auth/analytics",
// See and download your Google Analytics data
"https://www.googleapis.com/auth/analytics.readonly",
];
const constructReport = row => {
return {
path: decodeURIComponent(String(row?.dimensionValues?.[0]?.value)),
value: Number(row?.metricValues?.[0].value),
};
}
async function getReport(pluginOptions) {
let report = await executeAnalytics(pluginOptions);
return report.data.rows?.map(constructReport) || [];
}
async function executeAnalytics(pluginOptions) {
const jwt = new google.auth.JWT(
pluginOptions.serviceAccountEmail,
undefined,
pluginOptions.privateKey.replace(/\\n/gm, "\n"),
scopes
);
await jwt.authorize();
const analyticsReporting = google.analyticsdata({
version: "v1beta",
auth: jwt,
});
let metric = pluginOptions.metric || "screenPageViews";
let assignedDimension = pluginOptions.dimension || "pagePath";
let dimension = metric.startsWith("organicGoogleSearch") ? "landingPagePlusQueryString" : assignedDimension;
let regexFilter = pluginOptions.regexFilter;
const properties = analyticsReporting.properties;
return properties.runReport({
property: `properties/${pluginOptions.property}`,
requestBody: {
dimensions: [{ name: dimension }],
metrics: [{ name: metric }],
dateRanges: [{ startDate: pluginOptions.startDate || "365daysAgo", endDate: pluginOptions.endDate || "today" }],
dimensionFilter: {
orGroup: {
expressions: [
{
orGroup: {
expressions: [
{
filter: {
fieldName: dimension,
stringFilter: {
matchType: "PARTIAL_REGEXP",
value: regexFilter,
},
},
},
],
},
},
],
},
},
limit: pluginOptions.limit?.toString(),
orderBys: [{ metric: { metricName: metric }, desc: pluginOptions.desc ?? true }],
},
});
}