-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-node.js
64 lines (58 loc) · 1.45 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
const { google } = require('googleapis');
const defaultConfig = {
maxResults: 3,
filters:
'ga:pagePath!@/tag/;ga:pagePath!@/page/;ga:pagePath!=/;ga:pageTitle!=(not set);ga:pagePath!@&',
dates: { from: 'today', to: '2019-01-01' },
};
exports.sourceNodes = async (
{ actions: { createNode }, createNodeId, createContentDigest },
options
) => {
try {
const {
viewId,
email,
filters,
secretKey,
maxResults,
dates: { from, to },
} = {
...options,
...defaultConfig,
dates: { ...options.dates, ...defaultConfig.dates },
};
const auth = new google.auth.JWT(
email,
null,
secretKey.replace(/\\n/gm, '\n'),
['https://www.googleapis.com/auth/analytics.readonly']
);
await auth.authorize();
const res = await google.analytics('v3').data.ga.get({
auth,
filters,
'end-date': from,
'start-date': to,
ids: `ga:${viewId}`,
sort: '-ga:pageViews',
metrics: 'ga:pageviews',
'max-results': maxResults,
dimensions: 'ga:pagePath,ga:pageTitle',
});
res.data.rows.forEach(([url, title, totalViews]) =>
createNode({
id: createNodeId(`MostReadPosts-${title}`),
url,
title,
totalViews,
internal: {
type: `MostReadPosts`,
contentDigest: createContentDigest({ url, title, totalViews }),
},
})
);
} catch (err) {
console.info(err);
}
};