-
Notifications
You must be signed in to change notification settings - Fork 0
/
UsingClientLibraries.js
95 lines (89 loc) · 2.42 KB
/
UsingClientLibraries.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Service account credentials
process.env["GOOGLE_APPLICATION_CREDENTIALS"] =
"your ServiceAccountCredentials.json";
// Google Analytics 4 property ID
propertyId = "your propertyId";
// Imports the Google Analytics Data API client library.
const { BetaAnalyticsDataClient } = require("@google-analytics/data");
const analyticsDataClient = new BetaAnalyticsDataClient();
// The data import reports in Google Data API usually require 24 to 48 hours. Therefore, for accurate data, it is recommended to fetch data from two days ago.
const twoDaysAgo = new Date();
twoDaysAgo.setDate(twoDaysAgo.getDate() - 2);
const twoDaysAgoISO = twoDaysAgo.toISOString().split("T")[0];
// Get daily data.
async function DailyData() {
// AverageDailyTraffic
const [responseAverageDailyTraffic] = await analyticsDataClient.runReport({
property: `properties/${propertyId}`,
dateRanges: [
{
startDate: twoDaysAgoISO,
endDate: twoDaysAgoISO,
},
],
dimensions: [],
metrics: [
{
name: "activeUsers",
},
],
});
// AverageTimeOnPage
const [responseAverageTimeOnPage] = await analyticsDataClient.runReport({
property: `properties/${propertyId}`,
dateRanges: [
{
startDate: twoDaysAgoISO,
endDate: twoDaysAgoISO,
},
],
dimensions: [
{
name: "pageTitle",
},
],
metrics: [
{
name: "userEngagementDuration",
},
{
name: "activeUsers",
},
],
});
// AverageDailyTraffic
let AverageDailyTraffic =
responseAverageDailyTraffic.rows[0].metricValues[0].value;
// data
const dailyPageData = responseAverageTimeOnPage.rows;
// send data to SF
sendRequestToSF(AverageDailyTraffic, dailyPageData);
}
function sendRequestToSF(AverageDailyTraffic, dailyPageData) {
const url = "your salasForce endpoint/services/apexrest/GA_Test_GetData";
const data = {
twoDaysAgo: twoDaysAgoISO,
dailyTraffic: AverageDailyTraffic,
pageData: dailyPageData,
};
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error("Fetch error:", error);
});
}
DailyData();