-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgatsby-node.js
111 lines (93 loc) · 2.52 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
/* eslint consistent-return: 0, no-restricted-syntax: 0 */
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
const path = require(`path`)
const locales = {
en: {
path: 'en',
default: true,
},
pt: {
path: 'pt',
},
}
const getLocalizedPages = page =>
Object.keys(locales).map(lang => {
const localizedPath = locales[lang].default
? page.path
: locales[lang].path + page.path
return {
...page,
path: localizedPath,
context: {
locale: lang,
},
}
})
// Create duplicates for each page in each language
exports.onCreatePage = ({ page, boundActionCreators }) => {
const { createPage, deletePage } = boundActionCreators
return new Promise(resolve => {
deletePage(page)
const pages = getLocalizedPages(page)
pages.map(p => createPage(p))
resolve()
})
}
// Get image's relative path to JSON
exports.onCreateNode = ({ node, boundActionCreators }) => {
const { createNodeField } = boundActionCreators
if (node.internal.owner !== 'gatsby-transformer-json') {
return
}
// Get filename to find out the JSON locale
const fileName = node.id
.split('.json')[0]
.split('/')
.pop()
createNodeField({
node,
name: 'locale',
value: fileName,
})
Object.keys(node).map(key => {
const isString = typeof node[key] === 'string'
const hasImageExtension = /\.(gif|jpg|jpeg|tiff|png)$/i.test(node[key])
if (!isString || !hasImageExtension) {
return {}
}
// We need to find the file's path inside the 'data' folder
const jsonPartialPath = node.id
// Node id is full path with some more text in the end
// We split with 'data'
.split('/data')
// Get the last part (relative dir + filename and some string)
.pop()
// Split by /
.split('/')
// Remove last part (filename and some string)
.slice(0, -1)
// Join it again
.join('/')
const contentPath = path.join(__dirname, 'src/data', jsonPartialPath)
const imagePath = path.join(__dirname, 'static', node[key])
const relative = path.relative(contentPath, imagePath)
const existingValue = node.fields && node.fields[key]
let value
if (typeof existingValue === 'string') {
value = [existingValue, relative]
} else if (Array.isArray(existingValue)) {
value = [...existingValue, relative]
} else {
value = relative
}
return createNodeField({
node,
name: key,
value,
})
})
}