-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgatsby-node.js
75 lines (70 loc) · 1.93 KB
/
gatsby-node.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
const crypto = require('crypto');
const { google } = require('googleapis');
exports.sourceNodes = async ({ actions, createNodeId }, configOptions) => {
const { createNode } = actions;
const scopes = 'https://www.googleapis.com/auth/analytics.readonly';
const jwt = new google.auth.JWT(
configOptions.email,
null,
// fix netlify \n in env vars
// https://github.com/auth0/node-jsonwebtoken/issues/642#issuecomment-585173594
configOptions.privateKey.replace(/\\n/gm, '\n'),
scopes
);
await jwt.authorize();
const analyticsReporting = google.analyticsreporting({
version: 'v4',
auth: jwt,
});
const result = await analyticsReporting.reports.batchGet({
requestBody: {
reportRequests: [
{
viewId: configOptions.viewId,
dateRanges: [
{
startDate: configOptions.startDate || '2008-01-01',
endDate: configOptions.endDate || 'today',
},
],
metrics: [
{
expression: 'ga:pageviews',
},
],
dimensions: [
{
name: 'ga:pagePath',
},
],
orderBys: [
{
sortOrder: 'DESCENDING',
fieldName: 'ga:pageviews',
},
],
pageSize: configOptions.pageSize || 1000,
},
],
},
});
const { rows } = result.data.reports[0].data;
for (const { dimensions, metrics } of rows) {
const path = dimensions[0];
const totalCount = metrics[0].values[0];
createNode({
path,
totalCount: Number(totalCount),
id: createNodeId(path),
internal: {
type: `PageViews`,
contentDigest: crypto
.createHash(`md5`)
.update(JSON.stringify({ path, totalCount }))
.digest(`hex`),
mediaType: `text/plain`,
description: `Page views per path`,
},
});
}
};