Skip to content

Commit

Permalink
fix: prevent invalid graphql field names from being created
Browse files Browse the repository at this point in the history
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 gatsbyjs#3487; Fixes gatsbyjs#2925
  • Loading branch information
DSchau committed Feb 12, 2018
1 parent ab1d7f5 commit ea653be
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
24 changes: 24 additions & 0 deletions packages/gatsby/src/schema/__tests__/create-key.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const createKey = require(`../create-key`)

describe(`createKey`, () => {
it(`leaves valid strings as is`, () => {
;[
[`01234`, `01234`],
[`description`, `description`],
[`_hello`, `_hello`],
].forEach(([input, output]) => {
expect(createKey(input)).toBe(output)
})
})

it(`replaces invalid characters`, () => {
;[
[`/hello`, `_hello`],
[`~/path/to/some/module`, `_path_to_some_module`],
[`/*`, `_`],
[`/*.js`, `_js`],
].forEach(([input, output]) => {
expect(createKey(input)).toBe(output)
})
})
})
11 changes: 9 additions & 2 deletions packages/gatsby/src/schema/create-key.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow
const invariant = require(`invariant`)
const regex = new RegExp(`[^a-zA-Z0-9_]`, `g`)
const nonAlphaNumericExpr = new RegExp(`[^a-zA-Z0-9_]`, `g`)

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

return key.replace(regex, `_`)
const replaced = key.replace(nonAlphaNumericExpr, `_`)

// TODO: figure out what to replace this with _OR_ change the expr
if (replaced.match(/^__/)) {
return replaced.replace(/^_{2,}/, `_`)
}

return replaced
}
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ axios@^0.17.1:
follow-redirects "^1.2.5"
is-buffer "^1.1.5"

"axios@github:contentful/axios#fix/https-via-http-proxy":
axios@contentful/axios#fix/https-via-http-proxy:
version "0.17.1"
resolved "https://codeload.github.com/contentful/axios/tar.gz/4b06f4a63db3ac16c99f7c61b584ef0e6d11f1af"
dependencies:
Expand Down

0 comments on commit ea653be

Please sign in to comment.