Skip to content

Commit

Permalink
fix: prefix graphql type names with underscore if it starts with numb…
Browse files Browse the repository at this point in the history
…er (#10007)

if object or array is under field that starts with number it will cause graphql to fail with:
```
Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "6E0F4D382F504Ac5837DF8B7C8618485_2" does not.
```

to workaround it - prefix type name with `_` if it starts with number

fixes #9950

/cc @phonoman
  • Loading branch information
pieh committed Nov 19, 2018
1 parent b36c518 commit 1d2a9be
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
Expand Up @@ -87,6 +87,9 @@ describe(`GraphQL type inferance`, () => {
"with-hyphen": 2,
"with resolver": `1012-11-01`,
123: 42,
456: {
testingTypeNameCreation: true,
},
aBoolean: true,
externalUrl: `https://example.com/awesome.jpg`,
domain: `pizza.com`,
Expand Down Expand Up @@ -242,6 +245,9 @@ describe(`GraphQL type inferance`, () => {
with_hyphen
with_resolver(formatString:"DD.MM.YYYY")
_123
_456 {
testingTypeNameCreation
}
`
)

Expand All @@ -254,6 +260,7 @@ describe(`GraphQL type inferance`, () => {
expect(result.data.listNode[0].with_resolver).toEqual(`01.11.1012`)
expect(result.data.listNode[0]._123).toEqual(42)
expect(result.data.listNode[1]._123).toEqual(24)
expect(result.data.listNode[0]._456).toEqual(nodes[0][`456`])
})

describe(`Handles dates`, () => {
Expand Down
12 changes: 11 additions & 1 deletion packages/gatsby/src/schema/create-type-name.js
Expand Up @@ -2,8 +2,18 @@ const _ = require(`lodash`)

const seenNames = new Map()

const typeNameRestriction = /^[_a-zA-Z][_a-zA-Z0-9]*$/

module.exports = function createTypeName(name) {
const cameledName = _.camelCase(name)
let cameledName = _.camelCase(name)

// camelCasing will ensure that name is build from just alphanumeric
// characters, but we still need to ensure that type name
// doesn't start with number (graphql resitriction)
if (!cameledName.match(typeNameRestriction)) {
cameledName = `_` + cameledName
}

if (seenNames.has(cameledName)) {
seenNames.set(cameledName, seenNames.get(cameledName) + 1)
return `${cameledName}_${seenNames.get(cameledName)}`
Expand Down

0 comments on commit 1d2a9be

Please sign in to comment.