-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathurl-resolver.js
69 lines (62 loc) · 1.95 KB
/
url-resolver.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
/* @flow weak */
import { posix as path } from 'path'
import _ from 'lodash'
import invariant from 'invariant'
let rewritePath
try {
const gatsbyNodeConfig = path.resolve(process.cwd(), './gatsby-node')
// $FlowIssue - https://github.com/facebook/flow/issues/1975
const nodeConfig = require(gatsbyNodeConfig)
rewritePath = nodeConfig.rewritePath
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND' && !_.includes(e.Error, 'gatsby-node')) {
console.log(e)
}
}
export default function pathResolver (pageData, parsedPath) {
/**
* Determines if a hardcoded path was given in the frontmatter of a page.
*/
function hardcodedPath () {
if (pageData.path) {
const pathInvariantMessage = `
Hardcoded paths are relative to the website root so must be prepended with a
forward slash. You set the path to "${pageData.path}" in "${parsedPath.path}"
but it should be "/${pageData.path}"
See http://bit.ly/1qeNpdy for more.
`
invariant(pageData.path.charAt(0) === '/', pathInvariantMessage)
}
return pageData.path
}
/**
* Determines if the path should be rewritten using rules provided by the
* user in the gatsby-node.js config file in the root of the project.
*/
function rewrittenPath () {
if (rewritePath) {
return rewritePath(parsedPath, pageData)
} else { return undefined }
}
/**
* Determines the path of the page using the default of its location on the
* filesystem.
*/
function defaultPath () {
const { dirname } = parsedPath
let { name } = parsedPath
if (name === 'template' || name === 'index') {
name = ''
}
return path.join('/', dirname, name, '/')
}
/**
* Returns a path for a page. If the page name starts with an underscore,
* undefined is returned as it does not become a page.
*/
if (!_.startsWith(parsedPath.name, '_')) {
return hardcodedPath() || rewrittenPath() || defaultPath()
} else {
return undefined
}
}