-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
gatsby-node.js
69 lines (57 loc) · 1.82 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
const chokidar = require(`chokidar`)
const { createId, createFileNode } = require(`./create-file-node`)
exports.sourceNodes = (
{ boundActionCreators, getNode, hasNodeChanged, reporter },
pluginOptions
) => {
const { createNode, deleteNode } = boundActionCreators
let ready = false
const watcher = chokidar.watch(pluginOptions.path, {
ignored: [
`**/*.un~`,
`**/.gitignore`,
`**/.npmignore`,
`**/.babelrc`,
`**/yarn.lock`,
`**/node_modules`,
`../**/dist/**`,
],
})
const createAndProcessNode = path =>
createFileNode(path, pluginOptions).then(createNode)
// For every path that is reported before the 'ready' event, we throw them
// into a queue and then flush the queue when 'ready' event arrives.
// After 'ready', we handle the 'add' event without putting it into a queue.
let pathQueue = []
const flushPathQueue = () => {
let queue = pathQueue.slice()
pathQueue = []
return Promise.all(queue.map(createAndProcessNode))
}
watcher.on(`add`, path => {
if (ready) {
reporter.info(`added file at ${path}`)
createAndProcessNode(path).catch(err => reporter.error(err))
} else {
pathQueue.push(path)
}
})
watcher.on(`change`, path => {
reporter.info(`changed file at ${path}`)
createAndProcessNode(path).catch(err => reporter.error(err))
})
watcher.on(`unlink`, path => {
reporter.info(`file deleted at ${path}`)
const node = getNode(createId(path))
deleteNode(node.id, node)
// Also delete nodes for the file's transformed children nodes.
node.children.forEach(childId => deleteNode(childId, getNode(childId)))
})
return new Promise((resolve, reject) => {
watcher.on(`ready`, () => {
if (ready) return
ready = true
flushPathQueue().then(resolve, reject)
})
})
}