Last active
July 28, 2018 20:43
-
-
Save lkatney/1133b593a71ddfd9400d878aaa5e0471 to your computer and use it in GitHub Desktop.
Server-Server integration between NodeJS and Google APIs to get page views on pages and top viewed pages on your website
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var {google} = require('googleapis'), // official https://github.com/google/google-api-nodejs-client npm module | |
analyticsreporting = google.analyticsreporting('v4'), | |
key = require('./private.json');// Secure server key file(in JSON) dowloaded from Google | |
/********************** GET PAGE VIEWS *******************/ | |
app.get('/analytics/report', cors(corsOptions), function(req,res){ | |
//passed parameter | |
var url = req.query.url; | |
var jwtClient = new google.auth.JWT( | |
key.client_email, | |
null, | |
key.private_key, | |
['https://www.googleapis.com/auth/analytics.readonly'], // an array of auth scopes | |
null | |
); | |
jwtClient.authorize(function (err, tokens) { | |
if (err) { | |
console.log(err); | |
return; | |
} | |
// Make an authorized request to anayltics | |
var params = { | |
"auth": jwtClient, | |
"headers": { | |
"Content-Type": "application/json" | |
}, | |
"resource":{ | |
"reportRequests": [ | |
{ | |
"viewId": "yourViewId", // your view Id from goofle | |
"samplingLevel": "DEFAULT", | |
"filtersExpression": "ga:pagePath=="+url, // url passed in query parameter | |
"dateRanges": [ | |
{ | |
"startDate": "2008-03-05", | |
"endDate": "yesterday" | |
} | |
], | |
"metrics": [ | |
{ | |
"expression": "ga:pageviews", | |
"alias": "" | |
} | |
], | |
"dimensions": [ | |
{ | |
"name": "ga:pagePath" | |
} | |
] | |
} | |
] | |
} | |
}; | |
analyticsreporting.reports.batchGet(params, function(err, resp){ | |
if(resp){ | |
var count = resp.data.reports[0].data.totals[0].values[0]; // actual page view count for passed url | |
res.json({"count" : count}); | |
}else{ | |
res.json({"error" : true}); | |
} | |
}); | |
}); | |
}); | |
/********************** GET TOP POSTS **************************/ | |
app.get('/analytics/posts', cors(corsOptions), function(req,res){ | |
//passed parameter | |
var top = req.query.top || 15; | |
var jwtClient = new google.auth.JWT( | |
key.client_email, | |
null, | |
key.private_key, | |
['https://www.googleapis.com/auth/analytics.readonly'], // an array of auth scopes | |
null | |
); | |
jwtClient.authorize(function (err, tokens) { | |
if (err) { | |
console.log(err); | |
return; | |
} | |
// Make an authorized request to anayltics | |
var params = { | |
"auth": jwtClient, | |
"headers": { | |
"Content-Type": "application/json" | |
}, | |
"resource":{ | |
"reportRequests": [ | |
{ | |
"viewId": "yourViewId", // your view Id from goofle | |
"samplingLevel": "DEFAULT", | |
"dateRanges": [ | |
{ | |
"startDate": "2008-03-05", | |
"endDate": "yesterday" | |
} | |
], | |
"metrics": [ | |
{ | |
"expression": "ga:pageviews", | |
"alias": "" | |
} | |
], | |
"dimensions": [ | |
{ | |
"name": "ga:pagePath" | |
}, | |
{ | |
"name": "ga:pageTitle" // EXTRA DIMENSION TO GET THE TITLE OF PAGES | |
} | |
] | |
} | |
] | |
} | |
}; | |
analyticsreporting.reports.batchGet(params, function(err, resp){ | |
if(resp){ | |
var lst = orderLstInDesc(extractKeyDate(resp)); | |
res.json({top : lst.slice(0, top)}); | |
}else{ | |
res.json({"error" : true}); | |
} | |
}); | |
}); | |
}); | |
//Method to order json object with a attribute | |
function orderLstInDesc(json){ | |
var orderedLst = []; | |
var keysSorted = Object.keys(json).sort(function(a,b){return json[b].count-json[a].count}); | |
for(var i = 0; i < keysSorted.length; i++){ | |
//remove home page | |
if(keysSorted[i] !== 'total' && keysSorted[i] !== '/'){ | |
orderedLst.push({ | |
url : keysSorted[i], | |
title : json[keysSorted[i]].title, | |
count : json[keysSorted[i]].count | |
}); | |
} | |
} | |
return orderedLst; | |
} | |
//Array to exclude some pages like home page, about page etc. | |
var excludeTitles = [ | |
'home', | |
'about', | |
'contact' | |
]; | |
function checkKeywordsToExclude(title){ | |
for(var i = 0; i < excludeTitles.length; i++){ | |
if(title.toLowerCase().includes(excludeTitles[i].toLowerCase())){ | |
return true; | |
} | |
} | |
return false; | |
} | |
//returns a map of url with key information | |
//like title and page views on urls | |
//example : {"/path/to/page" : | |
// { "title" : "page title", "count" : 200} | |
// } | |
function extractKeyDate(data){ | |
var keyData = {}; | |
var lines = data.reports[0].data.rows; | |
for(var i = 0 ; i < lines.length; i++){ | |
var key = lines[i].dimensions[0]; | |
var title; | |
if(!checkKeywordsToExclude(lines[i].dimensions[1])){ | |
title = lines[i].dimensions[1]; | |
} | |
var val = parseInt(lines[i].metrics[0].values[0]); | |
if(keyData[key]){ | |
keyData[key].count += val; | |
keyData[key].title = title; | |
}else{ | |
keyData[key] = { title : title, count : val }; | |
} | |
} | |
return keyData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment