-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgatsby-node.ts
70 lines (61 loc) · 1.58 KB
/
gatsby-node.ts
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
import type {GatsbyNode} from 'gatsby'
import {shuffle} from './src/common/shuffle'
export const createPages: GatsbyNode['createPages'] = async ({
graphql,
cache
}) => {
const {data} = await graphql<{
allShopifyProduct: {
nodes: Array<{
id: string
tags: string[]
}>
}
}>(`
{
allShopifyProduct {
nodes {
id
tags
}
}
}
`)
const featuredProducts = shuffle(
data?.allShopifyProduct?.nodes || [],
29072003
)
const featuredProductIds = featuredProducts.slice(0, 12).map(({id}) => id)
// cache the featured product ids
cache.set(`featuredProductIds`, featuredProductIds)
}
export const onCreatePage: GatsbyNode['onCreatePage'] = async ({
page,
actions,
cache
}) => {
const {createPage, deletePage} = actions
const {path} = page
// && !page.context.featuredProductIds is a hack to prevent the onCreatePage
// from running into an infinite loop.. I have no idea why this is happening,
// but sadly it is. Gatsby should be able to handle this, but for some reason
// it doesn't.
// Ref: https://www.gatsbyjs.com/docs/creating-and-modifying-pages/
//
// 1 year later, maybe this is fixed now? I'll have to check.
if (path === '/' && !page.context?.featuredProductIds) {
deletePage(page)
// get featured products from cache
const featuredProductIds = (await cache.get(
`featuredProductIds`
)) as string[]
// create new page
createPage({
...page,
context: {
...page.context,
featuredProductIds
}
})
}
}