-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
199 lines (189 loc) · 5.1 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// Make environment variables defined in .env available on process.env
require('dotenv').config()
// Modules
const path = require('path')
const { createFilePath } = require('gatsby-source-filesystem')
const config = require('./config.js')
const eyes = require('eyes')
const _ = require('lodash')
const { google } = require('googleapis')
// Templates
const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)
const homePageTemplate = path.resolve('./src/templates/home.js')
// Analytics
const scopes = ['https://www.googleapis.com/auth/analytics.readonly']
const view_id = process.env.VIEW_ID
const jwt = new google.auth.JWT(
process.env.CLIENT_EMAIL,
null,
_.replace(process.env.PRIVATE_KEY, /\\n/g, '\n'),
scopes
)
async function getPageViews(startDate) {
const response = await jwt.authorize()
const results = await google.analytics('v3').data.ga.get({
auth: jwt,
ids: 'ga:' + view_id,
metrics: 'ga:uniquePageviews',
dimensions: 'ga:pagePath',
'start-date': startDate,
'end-date': 'yesterday',
sort: '-ga:uniquePageviews',
'max-results': 50
})
return results.data.rows
}
function removeNonPostPagesFromAnalytics(el) {
let relUrl = el[0]
let parts = relUrl.split('/')
if (
relUrl === '/' ||
relUrl === '/zzz/' ||
relUrl === '/zzz' ||
relUrl === '/abcxyz/' ||
relUrl === '/abcxyz' ||
relUrl === '/abc/' ||
relUrl === '/abc' ||
relUrl === '/about/' ||
relUrl === '/about' ||
relUrl === '/contact/' ||
relUrl === '/contact' ||
relUrl === '/tags/' ||
relUrl === '/tags'
) {
return false
}
if (parts[1] === 'tags') {
return false
}
if (Number(parts[1])) {
return false
}
return true
}
const createPostPages = (createPage, posts, pageViews) => {
posts.forEach(({ node }, index) => {
createPage({
path: node.frontmatter.path,
component: blogPostTemplate,
context: {
prev: index === 0 ? null : posts[index - 1].node,
next: index === posts.length - 1 ? null : posts[index + 1].node,
pageViews
}
})
})
}
const createTagPages = (createPage, posts, pageViews) => {
const tagTemplate = path.resolve(`src/templates/tag.js`)
const tagIndexTemplate = path.resolve(`src/templates/tag-index.js`)
const postsByTags = {}
posts.forEach(({ node }) => {
if (node.frontmatter.tags) {
node.frontmatter.tags.forEach(tag => {
if (!postsByTags[tag]) {
postsByTags[tag] = []
}
postsByTags[tag].push(node)
})
}
})
const tags = Object.keys(postsByTags)
createPage({
path: `/tags/`,
component: tagIndexTemplate,
context: {
tags: tags.sort(),
pageViews
}
})
tags.forEach(tagName => {
const posts = postsByTags[tagName]
createPage({
path: `/tags/${tagName}/`,
component: tagTemplate,
context: {
posts,
tagName,
pageViews
}
})
})
}
const createHomePages = (createPage, posts, pageViews) => {
const postsPerPage = config.postsPerPage
const numPages = Math.ceil(posts.length / postsPerPage)
Array.from({ length: numPages }).forEach((_, i) => {
createPage({
path: i === 0 ? `/` : `/${i + 1}/`,
component: homePageTemplate,
context: {
limit: postsPerPage,
skip: i * postsPerPage,
numPages,
currentPage: i + 1,
pageViews
}
})
})
}
exports.createPages = async ({ actions, graphql }) => {
const { createPage } = actions
const result = await graphql(`
{
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
html
id
headings {
value
depth
}
tableOfContents(pathToSlugField: "frontmatter.path")
frontmatter {
date
path
title
excerpt
tags
draft
}
}
}
}
}
`)
// After converting exports.createPages from promises to async/await, I'm
// not quite sure if this is the correct way to perform error handling.
if (result.errors) {
return Promise.reject(result.errors)
}
const posts = result.data.allMarkdownRemark.edges
const allowedPosts = posts.filter(post => {
if (process.env.NODE_ENV === 'production' && post.node.frontmatter.draft) {
return false
}
return true
})
const trending = await getPageViews('30daysAgo')
const allTime = await getPageViews('2005-01-01')
const pageViews = {
trending: trending.filter(removeNonPostPagesFromAnalytics).slice(0, 10),
allTime: allTime.filter(removeNonPostPagesFromAnalytics).slice(0, 10)
}
createPostPages(createPage, allowedPosts, pageViews)
createTagPages(createPage, allowedPosts, pageViews)
createHomePages(createPage, allowedPosts, pageViews)
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: 'slug',
node,
value
})
}
}