-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
validate-path-query.ts
54 lines (47 loc) · 1.74 KB
/
validate-path-query.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
import _ from "lodash"
import systemPath from "path"
export function validatePathQuery(
filePath: string,
extensions: Array<string>
): void {
// Paths must start with /
if (filePath.startsWith(`/`) !== true) {
throw new Error(`PageCreator: To query node "gatsbyPath" the "filePath" argument must be an absolute path, starting with a /
Please change this to: "/${filePath}"`)
}
// Paths must not include file extension
if (/\.[a-z]+$/i.test(filePath)) {
throw new Error(`PageCreator: To query node "gatsbyPath" the "filePath" argument must omit the file extension
Please change ${filePath} to "${filePath.replace(/\.[a-z]+$/i, ``)}"`)
}
// Paths must not utilize src/pages
if (filePath.includes(`src/pages`)) {
throw new Error(`PageCreator: To query node "gatsbyPath" the "filePath" argument must omit the src/pages prefix.
Please change this to: "${filePath.replace(/\/?src\/pages\//, ``)}"`)
}
// Paths must not include index
if (/index$/.test(filePath)) {
throw new Error(
`PageCreator: To query node "gatsbyPath" the "filePath" argument must omit index.
Please change this to: "${filePath.replace(/index$/, ``)}"`
)
}
const absolutePath = systemPath.join(process.cwd(), `src/pages`, filePath)
const file = _.flatten(
extensions.map(ext =>
[``, `${systemPath.sep}index`].map(index => {
try {
return require.resolve(absolutePath + index + ext)
} catch (e) {
return false
}
})
)
).filter(Boolean) as Array<string>
if (file.length === 0 || file[0].length === 0) {
throw new Error(
`PageCreator: To query node "gatsbyPath" the "filePath" argument must represent a file that exists.
Unable to find a file at: "${absolutePath}"`
)
}
}