Skip to content

Commit ea653be

Browse files
committed
fix: prevent invalid graphql field names from being created
Note: This will currently transform (for example) `/*` into `_` so I'm not quite sure what the best course of action is to replace that Fixes #3487; Fixes #2925
1 parent ab1d7f5 commit ea653be

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const createKey = require(`../create-key`)
2+
3+
describe(`createKey`, () => {
4+
it(`leaves valid strings as is`, () => {
5+
;[
6+
[`01234`, `01234`],
7+
[`description`, `description`],
8+
[`_hello`, `_hello`],
9+
].forEach(([input, output]) => {
10+
expect(createKey(input)).toBe(output)
11+
})
12+
})
13+
14+
it(`replaces invalid characters`, () => {
15+
;[
16+
[`/hello`, `_hello`],
17+
[`~/path/to/some/module`, `_path_to_some_module`],
18+
[`/*`, `_`],
19+
[`/*.js`, `_js`],
20+
].forEach(([input, output]) => {
21+
expect(createKey(input)).toBe(output)
22+
})
23+
})
24+
})

packages/gatsby/src/schema/create-key.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// @flow
22
const invariant = require(`invariant`)
3-
const regex = new RegExp(`[^a-zA-Z0-9_]`, `g`)
3+
const nonAlphaNumericExpr = new RegExp(`[^a-zA-Z0-9_]`, `g`)
44

55
/**
66
* GraphQL field names must be a string and cannot contain anything other than
@@ -14,5 +14,12 @@ module.exports = (key: string): string => {
1414
`Graphql field name (key) is not a string -> ${key}`
1515
)
1616

17-
return key.replace(regex, `_`)
17+
const replaced = key.replace(nonAlphaNumericExpr, `_`)
18+
19+
// TODO: figure out what to replace this with _OR_ change the expr
20+
if (replaced.match(/^__/)) {
21+
return replaced.replace(/^_{2,}/, `_`)
22+
}
23+
24+
return replaced
1825
}

yarn.lock

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,7 @@ axios@^0.17.1:
549549
follow-redirects "^1.2.5"
550550
is-buffer "^1.1.5"
551551

552-
"axios@github:contentful/axios#fix/https-via-http-proxy":
552+
axios@contentful/axios#fix/https-via-http-proxy:
553553
version "0.17.1"
554554
resolved "https://codeload.github.com/contentful/axios/tar.gz/4b06f4a63db3ac16c99f7c61b584ef0e6d11f1af"
555555
dependencies:

0 commit comments

Comments
 (0)