forked from styxlab/gatsby-theme-try-ghost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
291 lines (243 loc) · 10.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
const _ = require(`lodash`)
const { resolveUrl } = require(`./src/utils/routing`)
const { createContentDigest } = require(`gatsby-core-utils`)
const mediaConfigDefaults = require(`./src/utils/mediaConfigDefaults`)
const gatsbyNodeQuery = require(`./src/utils/gatsbyNodeQuery`)
const paginate = require(`./src/utils/pagination`)
const infiniteScroll = require(`./src/utils/infinite-scroll`)
exports.createSchemaCustomization = require(`./src/utils/create-schema-customization`)
exports.setFieldsOnGraphQLNodeType = require(`./src/utils/extend-node-type`)
// Simple logging
const useLog = (reporter, verbose, severity) => (message) => {
verbose && reporter[severity](message)
}
// Create pages
const createOrdinaryPages = (createOptions, pages, template) => {
const { createPage, basePath, log } = createOptions
pages.forEach(({ node }) => {
// Use url to analyze routing structure coming from Ghost CMS
const url = resolveUrl(basePath, `/`, node.slug, node.url)
createPage({
path: url,
component: template,
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: node.slug,
},
})
})
log(`createOrdinaryPages: finished`)
}
// Create post pages
const createPostPages = (createOptions, posts, tags, template, ampPath = ``) => {
const { createPage, log, basePath } = createOptions
const prevNodes = _.concat([{ node: { slug: `` } }],_.dropRight(posts))
const nextNodes = _.concat(_.drop(posts),[{ node: { slug: `` } }])
const collectionPaths = getCollectionPaths(posts.map(({ node }) => node.id), posts)
log(`createPostPages: ${posts.length > 0 && posts[0].node.title}`)
posts.forEach(({ node }, i) => {
const collectionPath = collectionPaths[node.id]
const url = resolveUrl(basePath, collectionPath, node.slug, node.url)
//total number of posts for primary tag
let primaryTagCount = _.find(tags, function (t) {
return node.primary_tag && t.node.slug === node.primary_tag.slug
})
primaryTagCount = primaryTagCount
&& primaryTagCount.node
&& primaryTagCount.node.postCount !== null ? primaryTagCount.node.postCount : 0
createPage({
path: `${url}${ampPath}`,
component: template,
context: {
slug: node.slug,
prev: prevNodes[i].node.slug,
next: nextNodes[i].node.slug,
tag: node.primary_tag && node.primary_tag.slug || ``,
limit: 3,
skip: 0,
primaryTagCount: primaryTagCount,
collectionPaths: collectionPaths,
},
})
})
log(`createPostPages: finished`)
}
// Create index page with pagination
const createIndexPage = (createOptions, posts, postIds, template, collectionPath = `/`) => {
const { createPage, log, basePath, iScrollEnabled, postsPerPage } = createOptions
const path = resolveUrl(basePath, collectionPath)
log(`createIndexPage: ${posts.length > 0 && posts[0].node.title}`)
paginate({
createPage,
totalItems: posts.length,
itemsPerPage: postsPerPage,
component: template,
pathPrefix: ({ pageNumber }) => (
pageNumber === 0 ? path : `${path}page`
),
context: {
collectionPath: collectionPath,
// Infinite Scroll
iScrollEnabled: iScrollEnabled,
postIds: postIds,
cursor: 0,
},
})
log(`createIndexPage: finished`)
}
// Create taxonomy pages (tags, authors)
const createTaxonomyPages = (createOptions, taxonomy, postIds, template, allPosts) => {
const { createPage, log, basePath, iScrollEnabled, postsPerPage } = createOptions
taxonomy.forEach(({ node }) => {
// Use url to analyze routing structure coming from Ghost CMS
const url = resolveUrl(basePath, `/`, node.slug, node.url)
const collectionPaths = getCollectionPaths(postIds[node.slug], allPosts)
paginate({
createPage,
totalItems: node.postCount,
itemsPerPage: postsPerPage,
component: template,
pathPrefix: ({ pageNumber }) => (
pageNumber === 0 ? url : `${url}page`
),
context: {
slug: node.slug,
collectionPaths: collectionPaths,
// Infinite Scroll
iScrollEnabled: iScrollEnabled,
postIds: postIds[node.slug],
cursor: 0,
},
})
})
log(`createTaxonomyPages: finished`)
}
/**
* Collections: Unique group of routes
*
*/
const createCollection = (createOptions, data, templates, allTags, collectionPath) => {
const { iScrollEnabled } = createOptions
// per collectionPath
createPostPages(createOptions, data.posts, allTags, templates.post)
const { indexIds } = infiniteScroll(iScrollEnabled, data.posts)
createIndexPage(createOptions, data.posts, indexIds, templates.index, collectionPath)
}
const getCollection = (data, collectionPath, selector = () => false) => {
const collection = data.posts.filter(({ node }) => selector(node))
collection.forEach(({ node }) => node.collectionPath = collectionPath)
const residualPosts = data.posts.filter(({ node }) => !selector(node))
residualPosts.forEach(({ node }) => node.collectionPath = `/`)
return ({
primary: {
posts: collection,
},
residual: {
posts: residualPosts,
},
})
}
const getCollectionPaths = (ids, posts) => {
const paths = {}
ids.forEach((id) => {
paths[id] = posts.find(({ node }) => node.id === id).node.collectionPath
})
return paths
}
const calcPostCounts = (data) => {
data.tags.forEach(({ node: tag }) => {
tag.postCount = data.posts.filter(({ node }) => node.tags.find(t => t.slug === tag.slug) !== undefined).length
})
data.authors.forEach(({ node: author }) => {
author.postCount = data.posts.filter(({ node }) => node.authors.find(a => a.slug === author.slug) !== undefined).length
})
}
/**
* Here is the place where Gatsby creates the URLs for all the
* posts, tags, pages and authors that we fetched from the Ghost site.
*/
exports.createPages = async ({ graphql, actions, reporter }, themeOptions) => {
const { createPage } = actions
const { routes, siteConfig } = themeOptions
const { verbose, severity, infiniteScroll: iScrollEnabled, excludePostsOrPages = (() => false) } = siteConfig
const basePath = routes && routes.basePath || `/`
const collections = routes && routes.collections || []
const log = useLog(reporter, verbose, severity)
/* Fragment are not yet possible here */
/* Further info 👉🏼 https://github.com/gatsbyjs/gatsby/issues/12155 */
const result = await graphql(`${gatsbyNodeQuery}`)
// Check for any errors
if (result.errors) {
throw new Error(result.errors)
}
log(`GraphQL data sucessfully fetched`)
// Extract query results
const postsPerPage = result.data.site.siteMetadata.postsPerPage
const createOptions = { createPage, log, basePath, iScrollEnabled, postsPerPage }
const data = {
pages: result.data.allGhostPage.edges,
posts: result.data.allGhostPost.edges,
tags: result.data.allGhostTag.edges,
authors: result.data.allGhostAuthor.edges,
}
// exclude posts or pages
data.posts = data.posts.filter(({ node }) => !excludePostsOrPages(node))
data.pages = data.pages.filter(({ node }) => !excludePostsOrPages(node))
calcPostCounts(data)
log(`createPages: ${data.posts.length > 0 && data.posts[0].node.title}`)
// Load templates
const templates = {
page: require.resolve(`./src/templates/page.js`),
post: require.resolve(`./src/templates/post.js`),
index: require.resolve(`./src/templates/index.js`),
tag: require.resolve(`./src/templates/tag.js`),
author: require.resolve(`./src/templates/author.js`),
}
createOrdinaryPages(createOptions, data.pages, templates.page)
// Split index pages by collections
let collectionData = data
collections.forEach((collection) => {
collectionData = getCollection(collectionData, collection.path, collection.selector)
createCollection(createOptions, collectionData.primary, templates, data.tags, collection.path)
collectionData = collectionData.residual
})
createCollection(createOptions, collectionData, templates, data.tags)
// Taxonomies are not split by collections
const { tagIds, authorIds } = infiniteScroll(iScrollEnabled, data.posts)
// Only use tags, authors present in posts (page only tags should not create tag/author pages)
const postTags = data.tags.filter(({ node }) => (node.postCount > 0 && node.slug.substr(0,5) !== `hash-`))
const postAuthors = data.authors.filter(({ node }) => node.postCount > 0)
createTaxonomyPages(createOptions, postTags, tagIds, templates.tag, data.posts)
createTaxonomyPages(createOptions, postAuthors, authorIds, templates.author, data.posts)
log(`createPages finished`)
}
// Plugins can access basePath with GraphQL query
exports.sourceNodes = ({ actions: { createTypes, createNode } }, { routes = {}, mediaConfig }) => {
const { basePath = `/` } = routes
const { gatsbyImageLoading, gatsbyImageFadeIn } = _.merge({}, mediaConfigDefaults, mediaConfig)
createTypes(`
type GhostConfig implements Node @dontinfer {
basePath: String!
gatsbyImageLoading: String
gatsbyImageFadeIn: Boolean
}
`)
const config = {
basePath: resolveUrl(basePath),
gatsbyImageLoading,
gatsbyImageFadeIn,
}
createNode({
...config,
id: `gatsby-theme-try-ghost-config`,
parent: null,
children: [],
internal: {
type: `ghostConfig`,
contentDigest: createContentDigest(config),
content: JSON.stringify(config),
description: `Ghost Config`,
},
})
}