Skip to content

Commit c7de340

Browse files
committed
Example on how to run Google Analytics PageView task for each API request
1 parent 374dc33 commit c7de340

File tree

3 files changed

+85
-2
lines changed

3 files changed

+85
-2
lines changed

index.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,22 @@ sessions.allowedResources = [
88
/\/users(\/.*)?/gi
99
];
1010

11-
sessions.init();
11+
sessions.init();
12+
13+
/**
14+
* Run Google Analytics on each API endpoint request
15+
*/
16+
module.context.use((req, res, next) =>
17+
{
18+
const {runTask} = module.context;
19+
runTask(
20+
'Google Analytics PageView recording',
21+
'ga',
22+
{
23+
clientId: req.headers['x-bb-client-request-uuid'],
24+
path: req.path,
25+
headers: req.headers
26+
});
27+
28+
next();
29+
});

manifest.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@
2121
"type": "integer",
2222
"description": "The time in seconds since the last update until a session will be considered expired"
2323
},
24-
24+
"googleAnalyticsId": {
25+
"default": "G-Y32FMJEM1W",
26+
"type": "string",
27+
"description": "Google Analytics Measurement ID"
28+
},
2529
"telegramToken": {
2630
"default": "xyz",
2731
"type": "string",

tasks/ga.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Google Analytics Measuring Task
3+
* @version 1.0
4+
* @author skitsanos
5+
*/
6+
7+
const request = require('@arangodb/request');
8+
const crypto = require('@arangodb/crypto');
9+
10+
/**
11+
*
12+
* @param clientId
13+
* @param path
14+
* @param headers
15+
* @param mount
16+
* @returns {boolean}
17+
*/
18+
const task = ({clientId, path, headers, context}) =>
19+
{
20+
const {googleAnalyticsId} = context.configuration;
21+
22+
if (Boolean(googleAnalyticsId))
23+
{
24+
//https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
25+
26+
const params = {
27+
v: '1',
28+
an: 'Foxx Microservices',
29+
aid: 'com.skitsanos.apps.foxx-builder',
30+
tid: googleAnalyticsId, //The measurement ID / web property ID
31+
cid: clientId || crypto.uuidv4(),
32+
t: 'pageview',
33+
ni: 1,
34+
dp: `${context.mount}${path}`,
35+
dt: `${context.mount}${path}`, //document title
36+
ds: 'api', //data source
37+
cm: 'organic',
38+
de: 'UTF-8', //document encoding
39+
ua: headers['user-agent'],
40+
uip: headers['client-ip'] || headers['remoteAddress']
41+
};
42+
43+
if (headers['x-country'])
44+
{
45+
params.geoid = headers['x-country'];
46+
}
47+
48+
console.log(params);
49+
request({
50+
method: 'get',
51+
url: 'https://www.google-analytics.com/collect',
52+
qs: params
53+
});
54+
55+
return true;
56+
}
57+
58+
return false;
59+
};
60+
61+
module.exports = task;

0 commit comments

Comments
 (0)