-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.js
More file actions
70 lines (60 loc) · 1.64 KB
/
Copy pathdata.js
File metadata and controls
70 lines (60 loc) · 1.64 KB
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
var dotenv = require('dotenv');
var _ = require('underscore');
var google = require('googleapis');
dotenv.load();
var authClient = new google.auth.JWT(
process.env.SERVICE_ACCOUNT_EMAIL,
null,
process.env.GOOGLE_SERVICE_KEY,
['https://www.googleapis.com/auth/analytics.readonly']
);
var analytics = google.analytics('v3');
var results = [];
function startGaClient() {
authClient.authorize(function (err, tokens) {
if(err) { console.log(err, tokens); }
gaListProfiles();
});
}
function gaListProfiles() {
analytics.management.profiles.list({
auth: authClient,
accountId: '~all',
webPropertyId: '~all'
}, function(err, data) {
if(err) { console.log(err, data); }
gaGetData(data)
});
}
function gaGetData(profilesData) {
var profileIds = profilesData.items.map(function(el) {
return el.id;
});
profileIds.forEach(function(profileId) {
analytics.data.ga.get({
auth: authClient,
'ids': 'ga:' + profileId,
'start-date': '7daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions,ga:pageviews'
}, function(err, data) {
if(err) { console.log(err, data); }
handleGaData(data);
});
});
}
function handleGaData(gaData) {
var result = {
profile: gaData.profileInfo.profileName,
results: gaData.totalsForAllResults
};
console.log('retrieved: ' + result.profile);
results.push(result);
}
function retrieveResults() {
return results;
}
module.exports = {
startGaClient: startGaClient,
retrieveResults: retrieveResults
};